diff --git a/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java index d0b4274731..813d8f20f8 100644 --- a/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java +++ b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java @@ -2,27 +2,26 @@ package com.baeldung.unzip; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class UnzipFile { - public static void main(String[] args) throws FileNotFoundException, IOException { - String fileZip = "/opt/zipped/cities.zip"; - byte[] buffer = new byte[1024]; - ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip)); + public static void main(final String[] args) throws IOException { + final String fileZip = "src/main/resources/compressed.zip"; + final byte[] buffer = new byte[1024]; + final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip)); ZipEntry zipEntry = zis.getNextEntry(); while(zipEntry != null){ - String fileName = zipEntry.getName(); - File newFile = new File("/opt/unzipped/" + fileName); - FileOutputStream fos = new FileOutputStream(newFile); + final String fileName = zipEntry.getName(); + final File newFile = new File("src/main/resources/unzipTest/" + fileName); + final FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } - fos.close(); + fos.close(); zipEntry = zis.getNextEntry(); } zis.closeEntry(); diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java b/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java new file mode 100644 index 0000000000..7da71a093d --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java @@ -0,0 +1,43 @@ +package com.baeldung.zip; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class ZipDirectory { + public static void main(final String[] args) throws IOException { + final String sourceFile = "src/main/resources/zipTest"; + final FileOutputStream fos = new FileOutputStream("src/main/resources/dirCompressed.zip"); + final ZipOutputStream zipOut = new ZipOutputStream(fos); + final File fileToZip = new File(sourceFile); + + zipFile(fileToZip, fileToZip.getName(), zipOut); + zipOut.close(); + fos.close(); + } + + private static void zipFile(final File fileToZip, final String fileName, final ZipOutputStream zipOut) throws IOException { + if (fileToZip.isHidden()) { + return; + } + if (fileToZip.isDirectory()) { + final File[] children = fileToZip.listFiles(); + for (final File childFile : children) { + zipFile(childFile, fileName + "/" + childFile.getName(), zipOut); + } + return; + } + final FileInputStream fis = new FileInputStream(fileToZip); + final ZipEntry zipEntry = new ZipEntry(fileName); + zipOut.putNextEntry(zipEntry); + final byte[] bytes = new byte[1024]; + int length; + while ((length = fis.read(bytes)) >= 0) { + zipOut.write(bytes, 0, length); + } + fis.close(); + } +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java index dccd3f2347..af80ec9609 100644 --- a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java +++ b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java @@ -2,22 +2,21 @@ package com.baeldung.zip; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipFile { - public static void main(String[] args) throws FileNotFoundException, IOException { - String sourceFile = "/opt/photos/photo.png"; - FileOutputStream fos = new FileOutputStream("/opt/zipped/cities.zip"); - ZipOutputStream zipOut = new ZipOutputStream(fos); - File fileToZip = new File(sourceFile); - FileInputStream fis = new FileInputStream(fileToZip); - ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); + public static void main(final String[] args) throws IOException { + final String sourceFile = "src/main/resources/zipTest/test1.txt"; + final FileOutputStream fos = new FileOutputStream("src/main/resources/compressed.zip"); + final ZipOutputStream zipOut = new ZipOutputStream(fos); + final File fileToZip = new File(sourceFile); + final FileInputStream fis = new FileInputStream(fileToZip); + final ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); - byte[] bytes = new byte[1024]; + final byte[] bytes = new byte[1024]; int length; while((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java b/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java new file mode 100644 index 0000000000..211696195d --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java @@ -0,0 +1,33 @@ +package com.baeldung.zip; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class ZipMultipleFiles { + public static void main(final String[] args) throws IOException { + final List srcFiles = Arrays.asList("src/main/resources/zipTest/test1.txt", "src/main/resources/zipTest/test2.txt"); + final FileOutputStream fos = new FileOutputStream("src/main/resources/multiCompressed.zip"); + final ZipOutputStream zipOut = new ZipOutputStream(fos); + for (final String srcFile : srcFiles) { + final File fileToZip = new File(srcFile); + final FileInputStream fis = new FileInputStream(fileToZip); + final ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); + zipOut.putNextEntry(zipEntry); + + final byte[] bytes = new byte[1024]; + int length; + while((length = fis.read(bytes)) >= 0) { + zipOut.write(bytes, 0, length); + } + fis.close(); + } + zipOut.close(); + fos.close(); + } +} \ No newline at end of file diff --git a/core-java-8/src/main/resources/compressed.zip b/core-java-8/src/main/resources/compressed.zip new file mode 100644 index 0000000000..03f840ae2b Binary files /dev/null and b/core-java-8/src/main/resources/compressed.zip differ diff --git a/core-java-8/src/main/resources/dirCompressed.zip b/core-java-8/src/main/resources/dirCompressed.zip new file mode 100644 index 0000000000..f42d3aa5c6 Binary files /dev/null and b/core-java-8/src/main/resources/dirCompressed.zip differ diff --git a/core-java-8/src/main/resources/multiCompressed.zip b/core-java-8/src/main/resources/multiCompressed.zip new file mode 100644 index 0000000000..002e70ef81 Binary files /dev/null and b/core-java-8/src/main/resources/multiCompressed.zip differ diff --git a/core-java-8/src/main/resources/unzipTest/test1.txt b/core-java-8/src/main/resources/unzipTest/test1.txt new file mode 100644 index 0000000000..c57eff55eb --- /dev/null +++ b/core-java-8/src/main/resources/unzipTest/test1.txt @@ -0,0 +1 @@ +Hello World! \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/test1.txt b/core-java-8/src/main/resources/zipTest/test1.txt new file mode 100644 index 0000000000..c57eff55eb --- /dev/null +++ b/core-java-8/src/main/resources/zipTest/test1.txt @@ -0,0 +1 @@ +Hello World! \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/test2.txt b/core-java-8/src/main/resources/zipTest/test2.txt new file mode 100644 index 0000000000..f0fb0f14d1 --- /dev/null +++ b/core-java-8/src/main/resources/zipTest/test2.txt @@ -0,0 +1 @@ +My Name is John \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/testFolder/test3.txt b/core-java-8/src/main/resources/zipTest/testFolder/test3.txt new file mode 100644 index 0000000000..882edb168e --- /dev/null +++ b/core-java-8/src/main/resources/zipTest/testFolder/test3.txt @@ -0,0 +1 @@ +My Name is Tom \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/testFolder/test4.txt b/core-java-8/src/main/resources/zipTest/testFolder/test4.txt new file mode 100644 index 0000000000..a78c3fadc8 --- /dev/null +++ b/core-java-8/src/main/resources/zipTest/testFolder/test4.txt @@ -0,0 +1 @@ +My Name is Jane \ No newline at end of file diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java index 35ec15df16..eb393668bd 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java @@ -1,5 +1,7 @@ package org.baeldung.java.io; +import static org.junit.Assert.assertEquals; + import java.io.IOException; import java.io.StringWriter; import java.io.Writer; @@ -23,6 +25,8 @@ public class JavaXToWriterUnitTest { final Writer targetWriter = new StringWriter().append(new String(initialArray)); targetWriter.close(); + + assertEquals("With Java", targetWriter.toString()); } @Test @@ -40,6 +44,8 @@ public class JavaXToWriterUnitTest { charSink.write(buffer); stringWriter.close(); + + assertEquals("With Guava", stringWriter.toString()); } @Test @@ -48,6 +54,8 @@ public class JavaXToWriterUnitTest { final Writer targetWriter = new StringBuilderWriter(new StringBuilder(new String(initialArray))); targetWriter.close(); + + assertEquals("With Commons IO", targetWriter.toString()); } } diff --git a/jackson/pom.xml b/jackson/pom.xml index e9008a81a7..f63ec08b48 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -60,7 +60,7 @@ com.fasterxml.jackson.module jackson-module-jsonSchema - 2.6.0 + 2.7.2 diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBean.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBean.java deleted file mode 100644 index ec67b3c67a..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBean.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.jackson.annotation.extra; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.annotation.JsonAppend; - -@JsonAppend(attrs = {@JsonAppend.Attr(value = "appendedProperty", include = JsonInclude.Include.ALWAYS)}) -public class AppendBean { - private int id; - private String name; - - public AppendBean(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBeans.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBeans.java new file mode 100644 index 0000000000..7b75c205c9 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBeans.java @@ -0,0 +1,58 @@ +package com.baeldung.jackson.annotation.extra; + +import com.fasterxml.jackson.databind.annotation.JsonAppend; + +public class AppendBeans { + public static class BeanWithoutAppend { + private int id; + private String name; + + public BeanWithoutAppend(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + @JsonAppend(attrs = { @JsonAppend.Attr(value = "version") }) + public static class BeanWithAppend { + private int id; + private String name; + + public BeanWithAppend(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationTest.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationTest.java index db6993da0f..79aae1dd04 100644 --- a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationTest.java @@ -1,38 +1,69 @@ package com.baeldung.jackson.annotation.extra; -import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import org.junit.Test; - +import com.baeldung.jackson.annotation.extra.AppendBeans.BeanWithAppend; +import com.baeldung.jackson.annotation.extra.AppendBeans.BeanWithoutAppend; +import com.baeldung.jackson.annotation.extra.IdentityReferenceBeans.BeanWithIdentityReference; +import com.baeldung.jackson.annotation.extra.IdentityReferenceBeans.BeanWithoutIdentityReference; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; +import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.module.jsonSchema.JsonSchema; import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper; public class ExtraAnnotationTest { + @Test + public void whenNotUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + BeanWithoutIdentityReference bean = new BeanWithoutIdentityReference(1, "Bean Without Identity Reference Annotation"); + String jsonString = mapper.writeValueAsString(bean); + + assertThat(jsonString, containsString("Bean Without Identity Reference Annotation")); + } + @Test public void whenUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); - IdentityReferenceBean bean = new IdentityReferenceBean(1, "Identity Reference Bean"); + BeanWithIdentityReference bean = new BeanWithIdentityReference(1, "Bean With Identity Reference Annotation"); String jsonString = mapper.writeValueAsString(bean); assertEquals("1", jsonString); } + @Test + public void whenNotUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + + BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation"); + ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class).withAttribute("version", "1.0"); + String jsonString = writer.writeValueAsString(bean); + + assertThat(jsonString, not(containsString("version"))); + assertThat(jsonString, not(containsString("1.0"))); + } + @Test public void whenUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); - AppendBean bean = new AppendBean(2, "Append Bean"); - String jsonString = mapper.writeValueAsString(bean); - assertThat(jsonString, containsString("appendedProperty")); + BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation"); + ObjectWriter writer = mapper.writerFor(BeanWithAppend.class).withAttribute("version", "1.0"); + String jsonString = writer.writeValueAsString(bean); + + assertThat(jsonString, containsString("version")); + assertThat(jsonString, containsString("1.0")); } @Test @@ -40,7 +71,7 @@ public class ExtraAnnotationTest { ObjectMapper mapper = new ObjectMapper(); NamingBean bean = new NamingBean(3, "Naming Bean"); String jsonString = mapper.writeValueAsString(bean); - + assertThat(jsonString, containsString("bean_name")); } @@ -51,7 +82,7 @@ public class ExtraAnnotationTest { mapper.acceptJsonFormatVisitor(PropertyDescriptionBean.class, wrapper); JsonSchema jsonSchema = wrapper.finalSchema(); String jsonString = mapper.writeValueAsString(jsonSchema); - + System.out.println(jsonString); assertThat(jsonString, containsString("This is a description of the name property")); } @@ -86,7 +117,7 @@ public class ExtraAnnotationTest { TypeIdResolverStructure.BeanContainer serializedContainer = new TypeIdResolverStructure.BeanContainer(); serializedContainer.setBeans(beans); - + ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(serializedContainer); assertThat(jsonString, containsString("bean1")); diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBean.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBean.java deleted file mode 100644 index 7f9cd0fdba..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBean.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.jackson.annotation.extra; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.JsonIdentityReference; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") -@JsonIdentityReference(alwaysAsId = true) -public class IdentityReferenceBean { - private int id; - private String name; - - public IdentityReferenceBean(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java new file mode 100644 index 0000000000..495bb7de43 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java @@ -0,0 +1,63 @@ +package com.baeldung.jackson.annotation.extra; + +import com.fasterxml.jackson.annotation.JsonIdentityInfo; +import com.fasterxml.jackson.annotation.JsonIdentityReference; +import com.fasterxml.jackson.annotation.ObjectIdGenerators; + + +public class IdentityReferenceBeans { + @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") + public static class BeanWithoutIdentityReference { + private int id; + private String name; + + public BeanWithoutIdentityReference(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") + @JsonIdentityReference(alwaysAsId = true) + public static class BeanWithIdentityReference { + private int id; + private String name; + + public BeanWithIdentityReference(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} \ No newline at end of file diff --git a/spring-mvc-xml/.classpath b/jooq-spring/.classpath similarity index 93% rename from spring-mvc-xml/.classpath rename to jooq-spring/.classpath index 6b533711d3..e43402fa4f 100644 --- a/spring-mvc-xml/.classpath +++ b/jooq-spring/.classpath @@ -6,29 +6,28 @@ - - - - - - + + + + + + + + + + + - - - - - - diff --git a/spring-data-redis/.project b/jooq-spring/.project similarity index 68% rename from spring-data-redis/.project rename to jooq-spring/.project index 06547e2b9c..3c3f3d602b 100644 --- a/spring-data-redis/.project +++ b/jooq-spring/.project @@ -1,6 +1,6 @@ - sprint-data-redis + jooq-spring @@ -10,11 +10,6 @@ - - org.springframework.ide.eclipse.core.springbuilder - - - org.eclipse.m2e.core.maven2Builder @@ -22,7 +17,6 @@ - org.springframework.ide.eclipse.core.springnature org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature diff --git a/jooq-spring/pom.xml b/jooq-spring/pom.xml new file mode 100644 index 0000000000..76198c4993 --- /dev/null +++ b/jooq-spring/pom.xml @@ -0,0 +1,153 @@ + + 4.0.0 + com.baeldung + jooq-spring + 0.0.1-SNAPSHOT + + + 3.7.3 + 1.4.191 + 4.2.5.RELEASE + 1.7.18 + 1.1.3 + 4.12 + + + + + + org.jooq + jooq + ${org.jooq.version} + + + + + com.h2database + h2 + ${com.h2database.version} + + + + + org.springframework + spring-context + ${org.springframework.version} + + + org.springframework + spring-jdbc + ${org.springframework.version} + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + runtime + + + ch.qos.logback + logback-classic + ${ch.qos.logback.version} + runtime + + + + + junit + junit + ${junit.version} + test + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + src/main/resources/intro_config.properties + + + + + + + + org.codehaus.mojo + sql-maven-plugin + 1.5 + + + initialize + + execute + + + ${db.driver} + ${db.url} + ${db.username} + ${db.password} + + src/main/resources/intro_schema.sql + + + + + + + com.h2database + h2 + ${com.h2database.version} + + + + + + org.jooq + jooq-codegen-maven + ${org.jooq.version} + + + generate-sources + + generate + + + + ${db.driver} + ${db.url} + ${db.username} + ${db.password} + + + + com.baeldung.jooq.introduction.db + src/main/java + + + + + + + + + \ No newline at end of file diff --git a/jooq-spring/src/main/resources/intro_config.properties b/jooq-spring/src/main/resources/intro_config.properties new file mode 100644 index 0000000000..3275089585 --- /dev/null +++ b/jooq-spring/src/main/resources/intro_config.properties @@ -0,0 +1,8 @@ +#Database Configuration +db.driver=org.h2.Driver +db.url=jdbc:h2:~/jooq +db.username=sa +db.password= + +#SQL Dialect +jooq.sql.dialect=H2 \ No newline at end of file diff --git a/jooq-spring/src/main/resources/intro_schema.sql b/jooq-spring/src/main/resources/intro_schema.sql new file mode 100644 index 0000000000..0d4bd26235 --- /dev/null +++ b/jooq-spring/src/main/resources/intro_schema.sql @@ -0,0 +1,34 @@ +DROP TABLE IF EXISTS author_book, author, book; + +CREATE TABLE author ( + id INT NOT NULL PRIMARY KEY, + first_name VARCHAR(50), + last_name VARCHAR(50) NOT NULL +); + +CREATE TABLE book ( + id INT NOT NULL PRIMARY KEY, + title VARCHAR(100) NOT NULL +); + +CREATE TABLE author_book ( + author_id INT NOT NULL, + book_id INT NOT NULL, + + PRIMARY KEY (author_id, book_id), + CONSTRAINT fk_ab_author FOREIGN KEY (author_id) REFERENCES author (id) + ON UPDATE CASCADE ON DELETE CASCADE, + CONSTRAINT fk_ab_book FOREIGN KEY (book_id) REFERENCES book (id) +); + +INSERT INTO author VALUES + (1, 'Kathy', 'Sierra'), + (2, 'Bert', 'Bates'), + (3, 'Bryan', 'Basham'); + +INSERT INTO book VALUES + (1, 'Head First Java'), + (2, 'Head First Servlets and JSP'), + (3, 'OCA/OCP Java SE 7 Programmer'); + +INSERT INTO author_book VALUES (1, 1), (1, 3), (2, 1); \ No newline at end of file diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java new file mode 100644 index 0000000000..7bee21f077 --- /dev/null +++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java @@ -0,0 +1,19 @@ +package com.baeldung.jooq.introduction; + +import org.jooq.ExecuteContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DefaultExecuteListener; + +import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator; +import org.springframework.jdbc.support.SQLExceptionTranslator; + +public class ExceptionTranslator extends DefaultExecuteListener { + private static final long serialVersionUID = 649359748808106775L; + + @Override + public void exception(ExecuteContext context) { + SQLDialect dialect = context.configuration().dialect(); + SQLExceptionTranslator translator = new SQLErrorCodeSQLExceptionTranslator(dialect.name()); + context.exception(translator.translate("Access database using jOOQ", context.sql(), context.sqlException())); + } +} \ No newline at end of file diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java new file mode 100644 index 0000000000..ee34c00679 --- /dev/null +++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java @@ -0,0 +1,76 @@ +package com.baeldung.jooq.introduction; + +import javax.sql.DataSource; +import org.h2.jdbcx.JdbcDataSource; +import org.jooq.SQLDialect; +import org.jooq.impl.DataSourceConnectionProvider; +import org.jooq.impl.DefaultConfiguration; +import org.jooq.impl.DefaultDSLContext; +import org.jooq.impl.DefaultExecuteListenerProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@ComponentScan({ "com.baeldung.jooq.introduction.db.public_.tables" }) +@EnableTransactionManagement +@PropertySource("classpath:intro_config.properties") +public class PersistenceContext { + @Autowired + private Environment environment; + + @Bean + public DataSource dataSource() { + JdbcDataSource dataSource = new JdbcDataSource(); + + dataSource.setUrl(environment.getRequiredProperty("db.url")); + dataSource.setUser(environment.getRequiredProperty("db.username")); + dataSource.setPassword(environment.getRequiredProperty("db.password")); + + return dataSource; + } + + @Bean + public TransactionAwareDataSourceProxy transactionAwareDataSource() { + return new TransactionAwareDataSourceProxy(dataSource()); + } + + @Bean + public DataSourceTransactionManager transactionManager() { + return new DataSourceTransactionManager(dataSource()); + } + + @Bean + public DataSourceConnectionProvider connectionProvider() { + return new DataSourceConnectionProvider(transactionAwareDataSource()); + } + + @Bean + public ExceptionTranslator exceptionTransformer() { + return new ExceptionTranslator(); + } + + @Bean + public DefaultDSLContext dsl() { + return new DefaultDSLContext(configuration()); + } + + @Bean + public DefaultConfiguration configuration() { + DefaultConfiguration jooqConfiguration = new DefaultConfiguration(); + jooqConfiguration.set(connectionProvider()); + jooqConfiguration.set(new DefaultExecuteListenerProvider(exceptionTransformer())); + + String sqlDialectName = environment.getRequiredProperty("jooq.sql.dialect"); + SQLDialect dialect = SQLDialect.valueOf(sqlDialectName); + jooqConfiguration.set(dialect); + + return jooqConfiguration; + } +} \ No newline at end of file diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java new file mode 100644 index 0000000000..bc12dff5a0 --- /dev/null +++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java @@ -0,0 +1,85 @@ +package com.baeldung.jooq.introduction; + +import com.baeldung.jooq.introduction.db.public_.tables.Author; +import com.baeldung.jooq.introduction.db.public_.tables.AuthorBook; +import com.baeldung.jooq.introduction.db.public_.tables.Book; +import org.jooq.DSLContext; +import org.jooq.Record3; +import org.jooq.Result; +import org.jooq.impl.DSL; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +import static org.junit.Assert.assertEquals; + +@ContextConfiguration(classes = PersistenceContext.class) +@Transactional(transactionManager = "transactionManager") +@RunWith(SpringJUnit4ClassRunner.class) +public class QueryTest { + + @Autowired + private DSLContext dsl; + + Author author = Author.AUTHOR; + Book book = Book.BOOK; + AuthorBook authorBook = AuthorBook.AUTHOR_BOOK; + + @Test + public void givenValidData_whenInserting_thenSucceed() { + dsl.insertInto(author).set(author.ID, 4).set(author.FIRST_NAME, "Herbert").set(author.LAST_NAME, "Schildt").execute(); + dsl.insertInto(book).set(book.ID, 4).set(book.TITLE, "A Beginner's Guide").execute(); + dsl.insertInto(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 4).execute(); + Result> result = dsl.select(author.ID, author.LAST_NAME, DSL.count()).from(author).join(authorBook).on(author.ID.equal(authorBook.AUTHOR_ID)).join(book).on(authorBook.BOOK_ID.equal(book.ID)) + .groupBy(author.LAST_NAME).fetch(); + + assertEquals(3, result.size()); + assertEquals("Sierra", result.getValue(0, author.LAST_NAME)); + assertEquals(Integer.valueOf(2), result.getValue(0, DSL.count())); + assertEquals("Schildt", result.getValue(2, author.LAST_NAME)); + assertEquals(Integer.valueOf(1), result.getValue(2, DSL.count())); + } + + @Test(expected = DataAccessException.class) + public void givenInvalidData_whenInserting_thenFail() { + dsl.insertInto(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 5).execute(); + } + + @Test + public void givenValidData_whenUpdating_thenSucceed() { + dsl.update(author).set(author.LAST_NAME, "Baeldung").where(author.ID.equal(3)).execute(); + dsl.update(book).set(book.TITLE, "Building your REST API with Spring").where(book.ID.equal(3)).execute(); + dsl.insertInto(authorBook).set(authorBook.AUTHOR_ID, 3).set(authorBook.BOOK_ID, 3).execute(); + Result> result = dsl.select(author.ID, author.LAST_NAME, book.TITLE).from(author).join(authorBook).on(author.ID.equal(authorBook.AUTHOR_ID)).join(book).on(authorBook.BOOK_ID.equal(book.ID)).where(author.ID.equal(3)) + .fetch(); + + assertEquals(1, result.size()); + assertEquals(Integer.valueOf(3), result.getValue(0, author.ID)); + assertEquals("Baeldung", result.getValue(0, author.LAST_NAME)); + assertEquals("Building your REST API with Spring", result.getValue(0, book.TITLE)); + } + + @Test(expected = DataAccessException.class) + public void givenInvalidData_whenUpdating_thenFail() { + dsl.update(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 5).execute(); + } + + @Test + public void givenValidData_whenDeleting_thenSucceed() { + dsl.delete(author).where(author.ID.lt(3)).execute(); + Result> result = dsl.select(author.ID, author.FIRST_NAME, author.LAST_NAME).from(author).fetch(); + + assertEquals(1, result.size()); + assertEquals("Bryan", result.getValue(0, author.FIRST_NAME)); + assertEquals("Basham", result.getValue(0, author.LAST_NAME)); + } + + @Test(expected = DataAccessException.class) + public void givenInvalidData_whenDeleting_thenFail() { + dsl.delete(book).where(book.ID.equal(1)).execute(); + } +} \ No newline at end of file diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java index 78e4083a28..3857056b70 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java @@ -1,5 +1,6 @@ package com.baeldung.spring.data.es.config; +import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.node.NodeBuilder; import org.slf4j.Logger; @@ -17,20 +18,14 @@ import java.nio.file.Path; import java.nio.file.Paths; @Configuration -@EnableElasticsearchRepositories(basePackages = "com.baeldung.repository") +@EnableElasticsearchRepositories(basePackages = "com.baeldung.spring.data.es.repository") @ComponentScan(basePackages = {"com.baeldung.spring.data.es.service"}) public class Config { private static Logger logger = LoggerFactory.getLogger(Config.class); @Bean - public NodeBuilder nodeBuilder() { - return new NodeBuilder(); - } - - @Bean - public ElasticsearchOperations elasticsearchTemplate() { - + public Client client() { try { Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data"); @@ -40,14 +35,19 @@ public class Config { logger.debug(tmpDir.toAbsolutePath().toString()); - return new ElasticsearchTemplate(nodeBuilder() + return new NodeBuilder() .local(true) .settings(elasticsearchSettings.build()) .node() - .client()); + .client(); } catch (IOException ioex) { logger.error("Cannot create temp dir", ioex); throw new RuntimeException(); } } + + @Bean + public ElasticsearchOperations elasticsearchTemplate() { + return new ElasticsearchTemplate(client()); + } } diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java deleted file mode 100644 index 313eba5b36..0000000000 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.spring.data.es.dao; - -import com.baeldung.spring.data.es.model.Article; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.elasticsearch.annotations.Query; -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; - -public interface ArticleRepository extends ElasticsearchRepository { - - Page
findByAuthorsName(String name, Pageable pageable); - - @Query("{\"bool\": {\"must\": [{\"match\": {\"authors.name\": \"?0\"}}]}}") - Page
findByAuthorsNameUsingCustomQuery(String name, Pageable pageable); -} diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java index dd472982ce..40db51ac13 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java @@ -1,23 +1,35 @@ package com.baeldung.spring.data.es.model; import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.FieldIndex; -import org.springframework.data.elasticsearch.annotations.FieldType; +import org.springframework.data.elasticsearch.annotations.*; +import java.util.Arrays; import java.util.List; +import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed; +import static org.springframework.data.elasticsearch.annotations.FieldType.Nested; +import static org.springframework.data.elasticsearch.annotations.FieldType.String; + @Document(indexName = "blog", type = "article") public class Article { @Id private String id; - @Field(type = FieldType.String, index = FieldIndex.not_analyzed) + + @MultiField( + mainField = @Field(type = String), + otherFields = { + @NestedField(index = not_analyzed, dotSuffix = "verbatim", type = String) + } + ) private String title; - @Field(type = FieldType.Nested) + + @Field(type = Nested) private List authors; + @Field(type = String, index = not_analyzed) + private String[] tags; + public Article() { } @@ -49,12 +61,21 @@ public class Article { this.authors = authors; } + public String[] getTags() { + return tags; + } + + public void setTags(String... tags) { + this.tags = tags; + } + @Override public String toString() { return "Article{" + "id='" + id + '\'' + ", title='" + title + '\'' + ", authors=" + authors + + ", tags=" + Arrays.toString(tags) + '}'; } } diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java index 27628950d7..8aef865401 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java @@ -5,7 +5,9 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.stereotype.Repository; +@Repository public interface ArticleRepository extends ElasticsearchRepository { Page
findByAuthorsName(String name, Pageable pageable); diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java new file mode 100644 index 0000000000..fbc18cbb4c --- /dev/null +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java @@ -0,0 +1,211 @@ +package com.baeldung.spring.data.es; + +import com.baeldung.spring.data.es.config.Config; +import com.baeldung.spring.data.es.model.Article; +import com.baeldung.spring.data.es.model.Author; +import com.baeldung.spring.data.es.service.ArticleService; +import org.elasticsearch.action.ActionFuture; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.unit.Fuzziness; +import org.elasticsearch.index.query.MultiMatchQueryBuilder; +import org.elasticsearch.index.query.QueryBuilder; +import org.elasticsearch.search.aggregations.Aggregation; +import org.elasticsearch.search.aggregations.AggregationBuilders; +import org.elasticsearch.search.aggregations.bucket.terms.StringTerms; +import org.elasticsearch.search.aggregations.bucket.terms.Terms; +import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; +import org.springframework.data.elasticsearch.core.query.SearchQuery; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static java.util.Arrays.asList; +import static java.util.stream.Collectors.toList; +import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND; +import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.junit.Assert.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {Config.class}, loader = AnnotationConfigContextLoader.class) +public class ElasticSearchQueryTest { + + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; + + @Autowired + private ArticleService articleService; + + @Autowired + private Client client; + + private final Author johnSmith = new Author("John Smith"); + private final Author johnDoe = new Author("John Doe"); + + @Before + public void before() { + elasticsearchTemplate.deleteIndex(Article.class); + elasticsearchTemplate.createIndex(Article.class); + elasticsearchTemplate.putMapping(Article.class); + elasticsearchTemplate.refresh(Article.class, true); + + Article article = new Article("Spring Data Elasticsearch"); + article.setAuthors(asList(johnSmith, johnDoe)); + article.setTags("elasticsearch", "spring data"); + articleService.save(article); + + article = new Article("Search engines"); + article.setAuthors(asList(johnDoe)); + article.setTags("search engines", "tutorial"); + articleService.save(article); + + article = new Article("Second Article About Elasticsearch"); + article.setAuthors(asList(johnSmith)); + article.setTags("elasticsearch", "spring data"); + articleService.save(article); + + article = new Article("Elasticsearch Tutorial"); + article.setAuthors(asList(johnDoe)); + article.setTags("elasticsearch"); + articleService.save(article); + } + + @Test + public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title", "Search engines").operator(AND)) + .build(); + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + } + + @Test + public void givenOneTermFromTitle_whenRunMatchQuery_thenDocIsFound() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title", "Engines Solutions")) + .build(); + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + assertEquals("Search engines", articles.get(0).getTitle()); + } + + @Test + public void givenPartTitle_whenRunMatchQuery_thenDocIsFound() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title", "elasticsearch data")) + .build(); + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(3, articles.size()); + } + + @Test + public void givenFullTitle_whenRunMatchQueryOnVerbatimField_thenDocIsFound() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch")) + .build(); + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + + searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title.verbatim", "Second Article About")) + .build(); + articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(0, articles.size()); + } + + @Test + public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() { + QueryBuilder builder = nestedQuery("authors", + boolQuery().must(termQuery("authors.name", "smith"))); + + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); + List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + + assertEquals(2, articles.size()); + } + + @Test + public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() { + TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("title"); + SearchResponse response = client.prepareSearch("blog").setTypes("article") + .addAggregation(aggregation).execute().actionGet(); + + Map results = response.getAggregations().asMap(); + StringTerms topTags = (StringTerms) results.get("top_tags"); + + List keys = topTags.getBuckets().stream().map(b -> b.getKey()).collect(toList()); + Collections.sort(keys); + assertEquals(asList("about", "article", "data", "elasticsearch", + "engines", "search", "second", "spring", "tutorial"), keys); + } + + @Test + public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() { + TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags") + .order(Terms.Order.aggregation("_count", false)); + SearchResponse response = client.prepareSearch("blog").setTypes("article") + .addAggregation(aggregation).execute().actionGet(); + + Map results = response.getAggregations().asMap(); + StringTerms topTags = (StringTerms) results.get("top_tags"); + + List keys = topTags.getBuckets().stream().map(b -> b.getKey()).collect(toList()); + assertEquals(asList("elasticsearch", "spring data", "search engines", "tutorial"), keys); + } + + @Test + public void givenNotExactPhrase_whenUseSlop_thenQueryMatches() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1)) + .build(); + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + } + + @Test + public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title", "spring date elasticserch") + .operator(AND) + .fuzziness(Fuzziness.ONE) + .prefixLength(3)) + .build(); + + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + } + + @Test + public void givenMultimatchQuery_whenDoSearch_thenAllProvidedFieldsMatch() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(multiMatchQuery("tutorial") + .field("title") + .field("tags") + .type(MultiMatchQueryBuilder.Type.BEST_FIELDS)) + .build(); + + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(2, articles.size()); + } +} diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java index 34ccfd788e..7b48772d3f 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java @@ -21,6 +21,7 @@ import java.util.List; import static java.util.Arrays.asList; import static org.elasticsearch.index.query.FilterBuilders.regexpFilter; +import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -31,6 +32,7 @@ public class ElasticSearchTest { @Autowired private ElasticsearchTemplate elasticsearchTemplate; + @Autowired private ArticleService articleService; @@ -126,4 +128,13 @@ public class ElasticSearchTest { assertEquals(count - 1, articleService.count()); } + + @Test + public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title", "Search engines").operator(AND)) + .build(); + List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + } } diff --git a/spring-data-redis/pom.xml b/spring-data-redis/pom.xml index 56c83adcf7..25686fca16 100644 --- a/spring-data-redis/pom.xml +++ b/spring-data-redis/pom.xml @@ -1,16 +1,15 @@ - + + 4.0.0 - com.baeldung - sprint-data-redis - 0.0.1-SNAPSHOT + spring-data-redis + 1.0 jar UTF-8 - 4.2.5.RELEASE - 1.6.2.RELEASE 0.8.0 @@ -72,7 +71,6 @@ nosqlunit-redis ${nosqlunit.version} - diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java new file mode 100644 index 0000000000..4fd83a2bb6 --- /dev/null +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java @@ -0,0 +1,55 @@ +package com.baeldung.spring.data.redis.config; + +import com.baeldung.spring.data.redis.queue.MessagePublisher; +import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.listener.ChannelTopic; +import org.springframework.data.redis.listener.RedisMessageListenerContainer; +import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; +import org.springframework.data.redis.serializer.GenericToStringSerializer; + +@Configuration +@ComponentScan("com.baeldung.spring.data.redis") +public class RedisConfig { + + @Bean + JedisConnectionFactory jedisConnectionFactory() { + return new JedisConnectionFactory(); + } + + @Bean + public RedisTemplate redisTemplate() { + final RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(jedisConnectionFactory()); + template.setValueSerializer(new GenericToStringSerializer(Object.class)); + return template; + } + + @Bean + MessageListenerAdapter messageListener() { + return new MessageListenerAdapter(new RedisMessageSubscriber()); + } + + @Bean + RedisMessageListenerContainer redisContainer() { + final RedisMessageListenerContainer container = new RedisMessageListenerContainer(); + container.setConnectionFactory(jedisConnectionFactory()); + container.addMessageListener(messageListener(), topic()); + return container; + } + + @Bean + MessagePublisher redisPublisher() { + return new RedisMessagePublisher(redisTemplate(), topic()); + } + + @Bean + ChannelTopic topic() { + return new ChannelTopic("pubsub:queue"); + } +} diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/model/Student.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java similarity index 95% rename from spring-data-redis/src/main/java/org/baeldung/spring/data/redis/model/Student.java rename to spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java index acc96899ce..10ba0f5ef4 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/model/Student.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.redis.model; +package com.baeldung.spring.data.redis.model; import java.io.Serializable; diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java new file mode 100644 index 0000000000..9a42545d6c --- /dev/null +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java @@ -0,0 +1,7 @@ +package com.baeldung.spring.data.redis.queue; + + +public interface MessagePublisher { + + void publish(final String message); +} diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java new file mode 100644 index 0000000000..f4b3180a37 --- /dev/null +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.data.redis.queue; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.listener.ChannelTopic; +import org.springframework.stereotype.Service; + +@Service +public class RedisMessagePublisher implements MessagePublisher { + + @Autowired + private RedisTemplate redisTemplate; + @Autowired + private ChannelTopic topic; + + public RedisMessagePublisher() { + } + + public RedisMessagePublisher(final RedisTemplate redisTemplate, + final ChannelTopic topic) { + this.redisTemplate = redisTemplate; + this.topic = topic; + } + + public void publish(final String message) { + redisTemplate.convertAndSend(topic.getTopic(), message); + } +} diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java new file mode 100644 index 0000000000..849e1fb59f --- /dev/null +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.data.redis.queue; + +import org.springframework.data.redis.connection.Message; +import org.springframework.data.redis.connection.MessageListener; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class RedisMessageSubscriber implements MessageListener { + + public static List messageList = new ArrayList(); + + public void onMessage(final Message message, final byte[] pattern) { + messageList.add(message.toString()); + System.out.println("Message received: " + new String(message.getBody())); + } +} \ No newline at end of file diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java similarity index 55% rename from spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java rename to spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java index 9e5502f8e0..250c227f00 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java @@ -1,15 +1,13 @@ -package org.baeldung.spring.data.redis.repo; +package com.baeldung.spring.data.redis.repo; -import org.baeldung.spring.data.redis.model.Student; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Component; +import com.baeldung.spring.data.redis.model.Student; import java.util.Map; public interface StudentRepository { void saveStudent(Student person); - + void updateStudent(Student student); Student findStudent(String id); diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java similarity index 93% rename from spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java rename to spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java index 43294cae58..f13bef0f54 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java @@ -1,6 +1,6 @@ -package org.baeldung.spring.data.redis.repo; +package com.baeldung.spring.data.redis.repo; -import org.baeldung.spring.data.redis.model.Student; +import com.baeldung.spring.data.redis.model.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.RedisTemplate; diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java deleted file mode 100644 index a7e75a438a..0000000000 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung.spring.data.redis.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; - -@Configuration -@ComponentScan("org.baeldung.spring.data.redis") -public class RedisConfig { - - @Bean - JedisConnectionFactory jedisConnectionFactory() { - return new JedisConnectionFactory(); - } - - @Bean - public RedisTemplate redisTemplate() { - final RedisTemplate< String, Object> template = new RedisTemplate(); - template.setConnectionFactory(jedisConnectionFactory()); - return template; - } -} diff --git a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerTest.java b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerTest.java new file mode 100644 index 0000000000..403cf990e0 --- /dev/null +++ b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerTest.java @@ -0,0 +1,30 @@ +package com.baeldung.spring.data.redis; + +import com.baeldung.spring.data.redis.config.RedisConfig; +import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; +import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.UUID; + +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RedisConfig.class) +public class RedisMessageListenerTest { + + @Autowired + private RedisMessagePublisher redisMessagePublisher; + + @Test + public void testOnMessage() throws Exception { + String message = "Message " + UUID.randomUUID(); + redisMessagePublisher.publish(message); + Thread.sleep(100); + assertTrue(RedisMessageSubscriber.messageList.get(0).contains(message)); + } +} \ No newline at end of file diff --git a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/repo/StudentRepositoryTest.java b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryTest.java similarity index 93% rename from spring-data-redis/src/test/java/org/baeldung/spring/data/redis/repo/StudentRepositoryTest.java rename to spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryTest.java index 08540abd36..c32dfc7670 100644 --- a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/repo/StudentRepositoryTest.java +++ b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryTest.java @@ -1,8 +1,7 @@ -package org.baeldung.spring.data.redis.repo; +package com.baeldung.spring.data.redis.repo; -import org.baeldung.spring.data.redis.config.RedisConfig; -import org.baeldung.spring.data.redis.model.Student; -import org.junit.Before; +import com.baeldung.spring.data.redis.config.RedisConfig; +import com.baeldung.spring.data.redis.model.Student; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-data-rest/README.md b/spring-data-rest/README.md new file mode 100644 index 0000000000..d9be83113b --- /dev/null +++ b/spring-data-rest/README.md @@ -0,0 +1,11 @@ +# About this project +This project contains examples from the [Introduction to Spring Data REST](http://www.baeldung.com/spring-data-rest-intro) article from Baeldung. + +# Running the project +The application uses [Spring Boot](http://projects.spring.io/spring-boot/), so it is easy to run. You can start it any of a few ways: +* Run the `main` method from `SpringDataRestApplication` +* Use the Maven Spring Boot plugin: `mvn spring-boot:run` +* Package the application as a JAR and run it using `java -jar intro-spring-data-rest.jar` + +# Viewing the running application +To view the running application, visit [http://localhost:8080](http://localhost:8080) in your browser diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml new file mode 100644 index 0000000000..f7f28aa9f1 --- /dev/null +++ b/spring-data-rest/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + com.baeldung + intro-spring-data-rest + 1.0 + jar + + intro-spring-data-rest + Intro to Spring Data REST + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-data-rest + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + ${project.artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java b/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java new file mode 100644 index 0000000000..6e8e62f52c --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java @@ -0,0 +1,11 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringDataRestApplication { + public static void main(String[] args) { + SpringApplication.run(SpringDataRestApplication.class, args); + } +} diff --git a/spring-data-rest/src/main/java/com/baeldung/UserRepository.java b/spring-data-rest/src/main/java/com/baeldung/UserRepository.java new file mode 100644 index 0000000000..ebbf0d49ab --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/UserRepository.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +import java.util.List; + +@RepositoryRestResource(collectionResourceRel = "users", path = "users") +public interface UserRepository extends PagingAndSortingRepository { + List findByName(@Param("name") String name); +} diff --git a/spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java b/spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java new file mode 100644 index 0000000000..a7a35a2573 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java @@ -0,0 +1,41 @@ +package com.baeldung; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class WebsiteUser { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String name; + private String email; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/spring-data-rest/src/main/resources/application.properties b/spring-data-rest/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-mvc-java/.classpath b/spring-mvc-java/.classpath index 6b533711d3..a642d37ceb 100644 --- a/spring-mvc-java/.classpath +++ b/spring-mvc-java/.classpath @@ -1,37 +1,37 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index d1e24a4d3d..f53a07264d 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -57,6 +57,13 @@ slf4j-log4j12 ${org.slf4j.version} + + + commons-fileupload + commons-fileupload + 1.3.1 + + junit diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java b/spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java similarity index 90% rename from spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java rename to spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java index c59c4f060a..7ae37404be 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java @@ -1,4 +1,4 @@ -package org.baeldung.aop; +package com.baeldung.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; @@ -27,11 +27,11 @@ public class LoggingAspect { public void repositoryMethods() { } - @Pointcut("@annotation(org.baeldung.aop.annotations.Loggable)") + @Pointcut("@annotation(com.baeldung.aop.annotations.Loggable)") public void loggableMethods() { } - @Pointcut("@args(org.baeldung.aop.annotations.Entity)") + @Pointcut("@args(com.baeldung.aop.annotations.Entity)") public void methodsAcceptingEntities() { } diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java b/spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java similarity index 97% rename from spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java rename to spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java index 2d07e5a5f3..1f2076adff 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java @@ -1,4 +1,4 @@ -package org.baeldung.aop; +package com.baeldung.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java b/spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java similarity index 94% rename from spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java rename to spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java index 324605dab1..7791c63e7b 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java @@ -1,10 +1,10 @@ -package org.baeldung.aop; +package com.baeldung.aop; +import com.baeldung.events.FooCreationEvent; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; -import org.baeldung.events.FooCreationEvent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java b/spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Entity.java similarity index 86% rename from spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java rename to spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Entity.java index f964c3979e..61d91b0777 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Entity.java @@ -1,4 +1,4 @@ -package org.baeldung.aop.annotations; +package com.baeldung.aop.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java b/spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Loggable.java similarity index 87% rename from spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java rename to spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Loggable.java index ef2863957f..92aa950e58 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Loggable.java @@ -1,4 +1,4 @@ -package org.baeldung.aop.annotations; +package com.baeldung.aop.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java b/spring-mvc-java/src/main/java/com/baeldung/dao/FooDao.java similarity index 75% rename from spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java rename to spring-mvc-java/src/main/java/com/baeldung/dao/FooDao.java index f204440b2d..1d28b082ec 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java +++ b/spring-mvc-java/src/main/java/com/baeldung/dao/FooDao.java @@ -1,7 +1,7 @@ -package org.baeldung.dao; +package com.baeldung.dao; -import org.baeldung.aop.annotations.Loggable; -import org.baeldung.model.Foo; +import com.baeldung.aop.annotations.Loggable; +import com.baeldung.model.Foo; import org.springframework.stereotype.Repository; @Repository diff --git a/spring-mvc-java/src/main/java/org/baeldung/dialect/CustomDialect.java b/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java similarity index 86% rename from spring-mvc-java/src/main/java/org/baeldung/dialect/CustomDialect.java rename to spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java index e6d1ad6b74..0c6a7c3ae0 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/dialect/CustomDialect.java +++ b/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java @@ -1,9 +1,9 @@ -package org.baeldung.dialect; +package com.baeldung.dialect; import java.util.HashSet; import java.util.Set; -import org.baeldung.processor.NameProcessor; +import com.baeldung.processor.NameProcessor; import org.thymeleaf.dialect.AbstractDialect; import org.thymeleaf.processor.IProcessor; diff --git a/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java b/spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEvent.java similarity index 86% rename from spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java rename to spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEvent.java index af11f3a4be..5ea4b46c04 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java +++ b/spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEvent.java @@ -1,4 +1,4 @@ -package org.baeldung.events; +package com.baeldung.events; import org.springframework.context.ApplicationEvent; diff --git a/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java b/spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEventListener.java similarity index 94% rename from spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java rename to spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEventListener.java index 35dcfd2bc3..c0aa744bc1 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java +++ b/spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEventListener.java @@ -1,4 +1,4 @@ -package org.baeldung.events; +package com.baeldung.events; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/Employee.java b/spring-mvc-java/src/main/java/com/baeldung/model/Employee.java similarity index 97% rename from spring-mvc-java/src/main/java/org/baeldung/model/Employee.java rename to spring-mvc-java/src/main/java/com/baeldung/model/Employee.java index 5365068a89..d0f6b724eb 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/model/Employee.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/Employee.java @@ -1,4 +1,4 @@ -package org.baeldung.model; +package com.baeldung.model; import javax.xml.bind.annotation.XmlRootElement; diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java b/spring-mvc-java/src/main/java/com/baeldung/model/Foo.java similarity index 80% rename from spring-mvc-java/src/main/java/org/baeldung/model/Foo.java rename to spring-mvc-java/src/main/java/com/baeldung/model/Foo.java index 87bd7132e6..01f5f43f60 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/Foo.java @@ -1,6 +1,6 @@ -package org.baeldung.model; +package com.baeldung.model; -import org.baeldung.aop.annotations.Entity; +import com.baeldung.aop.annotations.Entity; @Entity public class Foo { diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/User.java b/spring-mvc-java/src/main/java/com/baeldung/model/User.java similarity index 90% rename from spring-mvc-java/src/main/java/org/baeldung/model/User.java rename to spring-mvc-java/src/main/java/com/baeldung/model/User.java index df549cd21d..dc4480c986 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/model/User.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.model; +package com.baeldung.model; public class User { private String firstname; diff --git a/spring-mvc-java/src/main/java/org/baeldung/processor/NameProcessor.java b/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java similarity index 94% rename from spring-mvc-java/src/main/java/org/baeldung/processor/NameProcessor.java rename to spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java index df9a4da7f0..9a7857198c 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/processor/NameProcessor.java +++ b/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java @@ -1,4 +1,4 @@ -package org.baeldung.processor; +package com.baeldung.processor; import org.thymeleaf.Arguments; import org.thymeleaf.dom.Element; diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java new file mode 100644 index 0000000000..c108a450ae --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java @@ -0,0 +1,93 @@ +package com.baeldung.spring.web.config; + +import java.util.HashSet; +import java.util.Set; + +import com.baeldung.dialect.CustomDialect; +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Description; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; +import org.thymeleaf.dialect.IDialect; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templateresolver.ServletContextTemplateResolver; + +@EnableWebMvc +@Configuration +public class ClientWebConfig extends WebMvcConfigurerAdapter { + + public ClientWebConfig() { + super(); + } + + // API + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + + registry.addViewController("/sample.html"); + } + + @Bean + public ViewResolver thymeleafViewResolver() { + final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + bean.setOrder(0); + return bean; + } + + @Bean + @Description("Thymeleaf template resolver serving HTML 5") + public ServletContextTemplateResolver templateResolver() { + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/templates/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } + + @Bean + @Description("Thymeleaf template engine with Spring integration") + public SpringTemplateEngine templateEngine() { + final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + final Set dialects = new HashSet<>(); + dialects.add(new CustomDialect()); + templateEngine.setAdditionalDialects(dialects); + return templateEngine; + } + + @Bean + @Description("Spring message resolver") + public MessageSource messageSource() { + final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + +} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java similarity index 88% rename from spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java rename to spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java index 6fd68394ea..9780575678 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.web.config; +package com.baeldung.spring.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -23,14 +23,13 @@ public class ContentManagementWebConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { - configurer.favorPathExtension(true). - favorParameter(false). + configurer.favorPathExtension(false). + favorParameter(true). parameterName("mediaType"). ignoreAcceptHeader(true). useJaf(false). - defaultContentType(MediaType.TEXT_HTML). + defaultContentType(MediaType.APPLICATION_JSON). mediaType("xml", MediaType.APPLICATION_XML). - mediaType("html", MediaType.TEXT_HTML). mediaType("json", MediaType.APPLICATION_JSON); } diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java new file mode 100644 index 0000000000..4a11ba986c --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java @@ -0,0 +1,50 @@ +package com.baeldung.spring.web.config; + +import java.util.Set; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.context.support.GenericWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class MainWebAppInitializer implements WebApplicationInitializer { + + private static final String TMP_FOLDER = "C:/Users/ivan/Desktop/tmp"; + private static final int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; // 5 MB + + /** + * Register and configure all Servlet container components necessary to power the web application. + */ + @Override + public void onStartup(final ServletContext sc) throws ServletException { + + // Create the 'root' Spring application context + final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); + root.scan("com.baeldung.spring.web.config"); + // root.getEnvironment().setDefaultProfiles("embedded"); + + // Manages the lifecycle of the root application context + sc.addListener(new ContextLoaderListener(root)); + + // Handles requests into the application + final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext())); + appServlet.setLoadOnStartup(1); + + // final MultipartConfigElement multipartConfigElement = new + // MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE, + // MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2); + // + // appServlet.setMultipartConfig(multipartConfigElement); + + final Set mappingConflicts = appServlet.addMapping("/"); + if (!mappingConflicts.isEmpty()) { + throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); + } + } + +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java similarity index 77% rename from spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java rename to spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 09e9cff917..693fd74f74 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -1,9 +1,10 @@ -package org.baeldung.spring.web.config; +package com.baeldung.spring.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; @@ -15,14 +16,26 @@ import org.springframework.web.servlet.view.XmlViewResolver; @Configuration @EnableWebMvc -@ComponentScan("org.baeldung.web") +@ComponentScan("com.baeldung.web") public class WebConfig extends WebMvcConfigurerAdapter { public WebConfig() { super(); } - // + // @Bean + // public StandardServletMultipartResolver multipartResolver() { + // return new StandardServletMultipartResolver(); + // } + + @Bean(name = "multipartResolver") + public CommonsMultipartResolver multipartResolver() { + + final CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + multipartResolver.setMaxUploadSize(100000); + + return multipartResolver; + } @Override public void addViewControllers(final ViewControllerRegistry registry) { @@ -56,4 +69,4 @@ public class WebConfig extends WebMvcConfigurerAdapter { return bean; } -} \ No newline at end of file +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/BeanA.java b/spring-mvc-java/src/main/java/com/baeldung/web/BeanA.java similarity index 89% rename from spring-mvc-java/src/main/java/org/baeldung/web/BeanA.java rename to spring-mvc-java/src/main/java/com/baeldung/web/BeanA.java index b6b6f49c16..79fac724f7 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/BeanA.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/BeanA.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/BeanB.java b/spring-mvc-java/src/main/java/com/baeldung/web/BeanB.java similarity index 83% rename from spring-mvc-java/src/main/java/org/baeldung/web/BeanB.java rename to spring-mvc-java/src/main/java/com/baeldung/web/BeanB.java index 49e5af4ccb..05c9560a0c 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/BeanB.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/BeanB.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.web; import org.springframework.stereotype.Component; diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java similarity index 76% rename from spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java rename to spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java index 8a41718b8c..38272b23cb 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -1,9 +1,9 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import java.util.HashMap; import java.util.Map; -import org.baeldung.model.Employee; +import com.baeldung.model.Employee; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; @@ -29,15 +29,6 @@ public class EmployeeController { return employeeMap.get(Id); } - @RequestMapping(value = "/employee/{Id}", method = RequestMethod.GET) - public String getEmployeeByIdHtmlView(@PathVariable final long Id, final ModelMap model) { - model.addAttribute("name", employeeMap.get(Id).getName()); - model.addAttribute("contactNumber", employeeMap.get(Id).getContactNumber()); - model.addAttribute("id", employeeMap.get(Id).getId()); - - return "employeeView"; - } - @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { if (result.hasErrors()) { diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/FileUploadController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/FileUploadController.java new file mode 100644 index 0000000000..bc9cf13c34 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/FileUploadController.java @@ -0,0 +1,32 @@ +package com.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +@Controller +public class FileUploadController { + + @RequestMapping(value = "/fileUpload", method = RequestMethod.GET) + public String displayForm() { + + return "fileUploadForm"; + } + + @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) + public String submit(@RequestParam("file") final MultipartFile file, final ModelMap modelMap) { + + modelMap.addAttribute("file", file); + return "fileUploadView"; + } + + @RequestMapping(value = "/uploadMultiFile", method = RequestMethod.POST) + public String submit(@RequestParam("files") final MultipartFile[] files, final ModelMap modelMap) { + + modelMap.addAttribute("files", files); + return "fileUploadView"; + } +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/UserController.java similarity index 90% rename from spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java rename to spring-mvc-java/src/main/java/com/baeldung/web/controller/UserController.java index da39a36adf..fda159f204 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/UserController.java @@ -1,6 +1,6 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; -import org.baeldung.model.User; +import com.baeldung.model.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java deleted file mode 100644 index db57b4716b..0000000000 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.baeldung.spring.web.config; - -import java.util.HashSet; -import java.util.Set; - -import org.baeldung.dialect.CustomDialect; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Description; -import org.springframework.context.support.ResourceBundleMessageSource; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; -import org.thymeleaf.dialect.IDialect; -import org.thymeleaf.spring4.SpringTemplateEngine; -import org.thymeleaf.spring4.view.ThymeleafViewResolver; -import org.thymeleaf.templateresolver.ServletContextTemplateResolver; - -@EnableWebMvc -@Configuration -public class ClientWebConfig extends WebMvcConfigurerAdapter { - - public ClientWebConfig() { - super(); - } - - // API - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - - registry.addViewController("/sample.html"); - } - - @Bean - public ViewResolver thymeleafViewResolver() { - final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(0); - return bean; - } - - @Bean - @Description("Thymeleaf template resolver serving HTML 5") - public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); - templateResolver.setPrefix("/WEB-INF/templates/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); - return templateResolver; - } - - @Bean - @Description("Thymeleaf template engine with Spring integration") - public SpringTemplateEngine templateEngine() { - final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); - final Set dialects = new HashSet<>(); - dialects.add(new CustomDialect()); - templateEngine.setAdditionalDialects(dialects); - return templateEngine; - } - - @Bean - @Description("Spring message resolver") - public MessageSource messageSource() { - final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); - messageSource.setBasename("messages"); - return messageSource; - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } - -} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java deleted file mode 100644 index 87502e2088..0000000000 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.spring.web.config; - -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.context.support.GenericWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -public class MainWebAppInitializer implements WebApplicationInitializer { - - /** - * Register and configure all Servlet container components necessary to power the web application. - */ - @Override - public void onStartup(final ServletContext sc) throws ServletException { - System.out.println("MainWebAppInitializer.onStartup()"); - - // Create the 'root' Spring application context - final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.scan("org.baeldung.spring.web.config"); - // root.getEnvironment().setDefaultProfiles("embedded"); - - // Manages the lifecycle of the root application context - sc.addListener(new ContextLoaderListener(root)); - - // Handles requests into the application - final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext())); - appServlet.setLoadOnStartup(1); - final Set mappingConflicts = appServlet.addMapping("/"); - if (!mappingConflicts.isEmpty()) { - throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); - } - } - -} diff --git a/spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml b/spring-mvc-java/src/main/resources/com/baeldung/aop/beans.xml similarity index 86% rename from spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml rename to spring-mvc-java/src/main/resources/com/baeldung/aop/beans.xml index 17c63e39e4..e6aa9d77c4 100644 --- a/spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml +++ b/spring-mvc-java/src/main/resources/com/baeldung/aop/beans.xml @@ -7,8 +7,8 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"> - - + + diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp new file mode 100644 index 0000000000..1414b824ff --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp @@ -0,0 +1,55 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + + File Upload Example + + + + +

Enter The File to Upload (Single file)

+ + + + + + + + + + + +
Select a file to upload
+ +
+ +
+ +

Enter The Files to Upload (Multiple files)

+ + + + + + + + + + + + + + + + + + + +
Select a file to upload
Select a file to upload
Select a file to upload
+ +
+ + + + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadView.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadView.jsp new file mode 100644 index 0000000000..d6f748c6af --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadView.jsp @@ -0,0 +1,36 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + + + + Spring MVC File Upload + + + +

Submitted File (Single)

+ + + + + + + + + +
OriginalFileName :${file.originalFilename}
Type :${file.contentType}
+
+ +

Submitted Files (Multiple)

+ + + + + + + + + + + +
OriginalFileName :${file.originalFilename}
Type :${file.contentType}
+ + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/web_old.xml b/spring-mvc-java/src/main/webapp/WEB-INF/web_old.xml index 016369ad27..c8b38fae30 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/web_old.xml +++ b/spring-mvc-java/src/main/webapp/WEB-INF/web_old.xml @@ -16,7 +16,7 @@ contextConfigLocation - org.baeldung.spring.web.config + com.baeldung.spring.web.config diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java similarity index 95% rename from spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java index b1c9867e41..19bf4d0fac 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java @@ -1,8 +1,8 @@ -package org.baeldung.aop; +package com.baeldung.aop; -import org.baeldung.config.TestConfig; -import org.baeldung.dao.FooDao; -import org.baeldung.model.Foo; +import com.baeldung.config.TestConfig; +import com.baeldung.dao.FooDao; +import com.baeldung.model.Foo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPerformanceTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java similarity index 95% rename from spring-mvc-java/src/test/java/org/baeldung/aop/AopPerformanceTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java index 69083c60a2..4ad5a3e1a6 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPerformanceTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java @@ -1,7 +1,7 @@ -package org.baeldung.aop; +package com.baeldung.aop; -import org.baeldung.config.TestConfig; -import org.baeldung.dao.FooDao; +import com.baeldung.config.TestConfig; +import com.baeldung.dao.FooDao; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java similarity index 90% rename from spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java index e691dbd32e..c075db9fc6 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java @@ -1,9 +1,9 @@ -package org.baeldung.aop; +package com.baeldung.aop; -import org.baeldung.config.TestConfig; -import org.baeldung.dao.FooDao; -import org.baeldung.events.FooCreationEventListener; -import org.baeldung.model.Foo; +import com.baeldung.config.TestConfig; +import com.baeldung.dao.FooDao; +import com.baeldung.events.FooCreationEventListener; +import com.baeldung.model.Foo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java similarity index 94% rename from spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java index 7ef25d743c..4d2df50d18 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java @@ -1,6 +1,6 @@ -package org.baeldung.aop; +package com.baeldung.aop; -import org.baeldung.dao.FooDao; +import com.baeldung.dao.FooDao; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,7 +21,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("/org/baeldung/aop/beans.xml") +@ContextConfiguration("/com/baeldung/aop/beans.xml") public class AopXmlConfigPerformanceTest { @Before diff --git a/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/config/TestConfig.java similarity index 67% rename from spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java rename to spring-mvc-java/src/test/java/com/baeldung/config/TestConfig.java index f9573b2add..641513a24a 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/config/TestConfig.java @@ -1,11 +1,11 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration -@ComponentScan(basePackages = { "org.baeldung.dao", "org.baeldung.aop", "org.baeldung.events" }) +@ComponentScan(basePackages = { "com.baeldung.dao", "com.baeldung.aop", "com.baeldung.events" }) @EnableAspectJAutoProxy public class TestConfig { } diff --git a/spring-mvc-xml/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-mvc-xml/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-mvc-xml/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-mvc-xml/.settings/.jsdtscope b/spring-mvc-xml/.settings/.jsdtscope deleted file mode 100644 index b46b9207a8..0000000000 --- a/spring-mvc-xml/.settings/.jsdtscope +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/spring-mvc-xml/.settings/org.eclipse.jdt.core.prefs b/spring-mvc-xml/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 5ff04b9f96..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,91 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=error -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=error -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/spring-mvc-xml/.settings/org.eclipse.jdt.ui.prefs b/spring-mvc-xml/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,55 +0,0 @@ -#Sat Jan 21 23:04:06 EET 2012 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=true -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=true -sp_cleanup.make_local_variable_final=true -sp_cleanup.make_parameters_final=true -sp_cleanup.make_private_fields_final=false -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=false -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/spring-mvc-xml/.settings/org.eclipse.m2e.core.prefs b/spring-mvc-xml/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/spring-mvc-xml/.settings/org.eclipse.m2e.wtp.prefs b/spring-mvc-xml/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.m2e.wtp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.common.component b/spring-mvc-xml/.settings/org.eclipse.wst.common.component deleted file mode 100644 index fc995759ac..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-mvc-xml/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 9ca0d1c1b7..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.validation.prefs b/spring-mvc-xml/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.wst.validation.prefs +++ /dev/null @@ -1,15 +0,0 @@ -DELEGATES_PREFERENCE=delegateValidatorList -USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.402.v201212031633 -disabled=06target -eclipse.preferences.version=1 -override=true -suspend=false -vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01 -vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01 -vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02 -vf.version=3 diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-mvc-xml/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.wst.ws.service.policy.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.ws.service.policy.projectEnabled=false diff --git a/spring-mvc-xml/.springBeans b/spring-mvc-xml/.springBeans deleted file mode 100644 index 7623a7e888..0000000000 --- a/spring-mvc-xml/.springBeans +++ /dev/null @@ -1,14 +0,0 @@ - - - 1 - - - - - - - src/main/webapp/WEB-INF/mvc-servlet.xml - - - - diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java index b5238b04d5..76351b96f7 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -8,10 +8,10 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration public class ClientWebConfig extends WebMvcConfigurerAdapter { - public ClientWebConfig() { - super(); - } + public ClientWebConfig() { + super(); + } - // API + // API } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java index 06b2c0e461..bee09b742a 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java @@ -1,6 +1,12 @@ package com.baeldung.spring; +import java.util.Locale; +import java.util.ResourceBundle; + +import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; +import org.springframework.context.support.MessageSourceResourceBundle; +import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -11,27 +17,40 @@ import org.springframework.web.servlet.view.JstlView; //@Configuration public class ClientWebConfigJava extends WebMvcConfigurerAdapter { - public ClientWebConfigJava() { - super(); - } + public ClientWebConfigJava() { + super(); + } - // API + @Bean + public MessageSource messageSource() { - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); + final ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); + ms.setBasenames("messages"); + return ms; + } - registry.addViewController("/sample.html"); - } + @Bean + public ResourceBundle getBeanResourceBundle() { - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + final Locale locale = Locale.getDefault(); + return new MessageSourceResourceBundle(messageSource(), locale); + } - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); - return bean; - } + registry.addViewController("/sample.html"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java index 753f243edb..aa25f47a2a 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java @@ -22,35 +22,24 @@ public class EmployeeController { @RequestMapping(value = "/employee", method = RequestMethod.GET) public ModelAndView showForm() { - return new ModelAndView("employeeHome", "employee", new Employee()); + return new ModelAndView("employeeHome", "employee", new Employee()); } @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { - return employeeMap.get(Id); - } - - @RequestMapping(value = "/employee/{Id}", method = RequestMethod.GET) - public String getEmployeeByIdHtmlView(@PathVariable final long Id, final ModelMap model) { - model.addAttribute("name", employeeMap.get(Id).getName()); - model.addAttribute("contactNumber", employeeMap.get(Id).getContactNumber()); - model.addAttribute("id", employeeMap.get(Id).getId()); - - return "employeeView"; + return employeeMap.get(Id); } @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", employee.getName()); - model.addAttribute("contactNumber", employee.getContactNumber()); - model.addAttribute("id", employee.getId()); - - employeeMap.put(employee.getId(), employee); - - return "employeeView"; + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("id", employee.getId()); + employeeMap.put(employee.getId(), employee); + return "employeeView"; } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java new file mode 100644 index 0000000000..cc9d66d4d4 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +public class HelloController extends AbstractController { + + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + ModelAndView model = new ModelAndView("helloworld"); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + + " using SimpleUrlHandlerMapping."); + + return model; + } +} diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java new file mode 100644 index 0000000000..614888ae42 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +public class HelloGuestController extends AbstractController { + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + ModelAndView model = new ModelAndView("helloworld"); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + + " using ControllerClassNameHandlerMapping."); + + return model; + } +} diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java new file mode 100644 index 0000000000..6ed3d06ab7 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +public class HelloWorldController extends AbstractController { + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + ModelAndView model = new ModelAndView("helloworld"); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + + " using BeanNameUrlHandlerMapping."); + + return model; + } +} diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java new file mode 100644 index 0000000000..5459481674 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +public class WelcomeController extends AbstractController { + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + + ModelAndView model = new ModelAndView("welcome"); + model.addObject("msg", " Baeldung's Spring Handler Mappings Guide.
This request was mapped" + + " using SimpleUrlHandlerMapping."); + + return model; + } +} \ No newline at end of file diff --git a/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml b/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml index 0fcd85e399..e68c88d19d 100644 --- a/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml +++ b/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml @@ -13,31 +13,30 @@ - - + class="org.springframework.web.servlet.view.InternalResourceViewResolver"> + + - - - - - - + class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> + + + + + + - - - - - - - + + + + + + - \ No newline at end of file + diff --git a/spring-mvc-xml/src/main/resources/webMvcConfig.xml b/spring-mvc-xml/src/main/resources/webMvcConfig.xml index 0947eec368..4f2407d097 100644 --- a/spring-mvc-xml/src/main/resources/webMvcConfig.xml +++ b/spring-mvc-xml/src/main/resources/webMvcConfig.xml @@ -25,4 +25,4 @@
- \ No newline at end of file + diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml index 4ba9642448..6cefb21961 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -1,6 +1,57 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> + + + + + + + + + + + + + + + + + + + + welcomeController + welcomeController + helloController + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/hello.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/hello.jsp new file mode 100644 index 0000000000..2acdae9b0f --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/hello.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Hello World + + +

Hello ${msg}

+
+

+ Go to spring handler mappings homepage + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/helloworld.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/helloworld.jsp new file mode 100644 index 0000000000..2eeabbe0ac --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/helloworld.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Hello World + + +

Hello World ${msg}

+
+

+ Go to spring handler mappings homepage + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp index 1d14658f93..535348b7d2 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp @@ -24,7 +24,7 @@

Welcome, Enter the Person Details

- + @@ -117,4 +117,4 @@ - \ No newline at end of file + diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp index 8e874fbd02..1f9ba86c69 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp @@ -61,6 +61,5 @@ ${person.notes} - - \ No newline at end of file + diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/welcome.jsp new file mode 100644 index 0000000000..348ca652ff --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/welcome.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Welcome Page + + +

Welcome to ${msg}

+
+

+ Go to spring handler mappings homepage + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/index.jsp b/spring-mvc-xml/src/main/webapp/index.jsp index 1ecfcec9d7..ce7b3107d8 100644 --- a/spring-mvc-xml/src/main/webapp/index.jsp +++ b/spring-mvc-xml/src/main/webapp/index.jsp @@ -12,6 +12,7 @@

Spring MVC Examples

diff --git a/spring-mvc-xml/src/main/webapp/spring-handler-index.jsp b/spring-mvc-xml/src/main/webapp/spring-handler-index.jsp new file mode 100644 index 0000000000..0fdd51d1ec --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/spring-handler-index.jsp @@ -0,0 +1,18 @@ + + + + + Welcome + + +

Spring Handler Mapping Examples

+

Click each link below to see how the request is mapped using the specified mapping: +

+
    +
  1. BeanNameUrlHandlerMapping - Mapping by bean name
  2. +
  3. SimpleUrlHandlerMapping
  4. +
  5. ControllerClassNameHandlerMapping - Mapping by controller name
  6. +
+Home + + \ No newline at end of file diff --git a/spring-data-redis/.classpath b/spring-security-client/spring-security-jsp-authentication/.classpath similarity index 92% rename from spring-data-redis/.classpath rename to spring-security-client/spring-security-jsp-authentication/.classpath index 9ae7bca0fc..0cad5db2d0 100644 --- a/spring-data-redis/.classpath +++ b/spring-security-client/spring-security-jsp-authentication/.classpath @@ -17,7 +17,7 @@ - + @@ -25,6 +25,7 @@ + diff --git a/spring-security-client/spring-security-jsp-authentication/.project b/spring-security-client/spring-security-jsp-authentication/.project new file mode 100644 index 0000000000..6fbbb8518e --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/.project @@ -0,0 +1,48 @@ + + + spring-security-jsp-authenticate + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-client/spring-security-jsp-authentication/pom.xml b/spring-security-client/spring-security-jsp-authentication/pom.xml new file mode 100644 index 0000000000..74de4d729b --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + com.baeldung + spring-security-jsp-authentication + 0.0.1-SNAPSHOT + war + + spring-security-jsp-authenticate + Spring Security JSP Authentication tag sample + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + javax.servlet + jstl + + + + org.springframework.security + spring-security-taglibs + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..4057a85f13 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.web.SpringBootServletInitializer; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..fa2a324146 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,23 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + +} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/resources/application.properties b/spring-security-client/spring-security-jsp-authentication/src/main/resources/application.properties new file mode 100644 index 0000000000..26a80c79f3 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port: 8081 +spring.mvc.view.prefix: /WEB-INF/jsp/ +spring.mvc.view.suffix: .jsp \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-security-client/spring-security-jsp-authentication/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 0000000000..90c00e980a --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,24 @@ + <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> + + + + +Spring Security JSP Authorize + + + + + +
+ Current user name: +
+ Current user roles: +
+ + \ No newline at end of file diff --git a/spring-data-elasticsearch/.classpath b/spring-security-client/spring-security-jsp-authorize/.classpath similarity index 92% rename from spring-data-elasticsearch/.classpath rename to spring-security-client/spring-security-jsp-authorize/.classpath index 698778fef3..0cad5db2d0 100644 --- a/spring-data-elasticsearch/.classpath +++ b/spring-security-client/spring-security-jsp-authorize/.classpath @@ -17,7 +17,7 @@
- + @@ -25,6 +25,7 @@ + diff --git a/spring-security-client/spring-security-jsp-authorize/.project b/spring-security-client/spring-security-jsp-authorize/.project new file mode 100644 index 0000000000..a526feb28e --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/.project @@ -0,0 +1,48 @@ + + + spring-security-jsp-authorize + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-client/spring-security-jsp-authorize/pom.xml b/spring-security-client/spring-security-jsp-authorize/pom.xml new file mode 100644 index 0000000000..25bb21b663 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + com.baeldung + spring-security-jsp-authorize + 0.0.1-SNAPSHOT + war + + spring-security-jsp-authorize + Spring Security JSP Authorize tag sample + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + javax.servlet + jstl + + + + org.springframework.security + spring-security-taglibs + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..4057a85f13 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.web.SpringBootServletInitializer; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..fa2a324146 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,23 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + +} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/resources/application.properties b/spring-security-client/spring-security-jsp-authorize/src/main/resources/application.properties new file mode 100644 index 0000000000..26a80c79f3 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port: 8081 +spring.mvc.view.prefix: /WEB-INF/jsp/ +spring.mvc.view.suffix: .jsp \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-security-client/spring-security-jsp-authorize/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 0000000000..08af845bd4 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,33 @@ + <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> + + + + +Spring Security JSP Authorize + + + + + +
+ + Only admins can see this message + + + + Only users can see this message + +
+ + + Only users who can call "/admin" URL can see this message + +
+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/.classpath b/spring-security-client/spring-security-jsp-config/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-data-elasticsearch/.project b/spring-security-client/spring-security-jsp-config/.project similarity index 51% rename from spring-data-elasticsearch/.project rename to spring-security-client/spring-security-jsp-config/.project index 09b9a781ed..9afe120f66 100644 --- a/spring-data-elasticsearch/.project +++ b/spring-security-client/spring-security-jsp-config/.project @@ -1,15 +1,25 @@ - spring-data-elasticsearch + spring-security-jsp-config + + org.eclipse.wst.jsdt.core.javascriptValidator + + + org.eclipse.jdt.core.javabuilder + + org.eclipse.wst.common.project.facet.core.builder + + + org.eclipse.m2e.core.maven2Builder @@ -20,10 +30,19 @@ + + org.eclipse.wst.validation.validationbuilder + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature org.springframework.ide.eclipse.core.springnature org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature diff --git a/spring-security-client/spring-security-jsp-config/pom.xml b/spring-security-client/spring-security-jsp-config/pom.xml new file mode 100644 index 0000000000..2416552d7c --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + com.baeldung + spring-security-jsp-config + 0.0.1-SNAPSHOT + war + + spring-security-jsp-config + Spring Security JSP configuration + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + javax.servlet + jstl + + + + org.springframework.security + spring-security-taglibs + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..4057a85f13 --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.web.SpringBootServletInitializer; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..fa2a324146 --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,23 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + +} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/src/main/resources/application.properties b/spring-security-client/spring-security-jsp-config/src/main/resources/application.properties new file mode 100644 index 0000000000..26a80c79f3 --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port: 8081 +spring.mvc.view.prefix: /WEB-INF/jsp/ +spring.mvc.view.suffix: .jsp \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-security-client/spring-security-jsp-config/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 0000000000..bd5ccb0c78 --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,21 @@ + + + + +Spring Security JSP + + + + + +
+ Welcome +
+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-mvc/.classpath b/spring-security-client/spring-security-mvc/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-client/spring-security-mvc/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-mvc-xml/.project b/spring-security-client/spring-security-mvc/.project similarity index 88% rename from spring-mvc-xml/.project rename to spring-security-client/spring-security-mvc/.project index de41bcaace..d675acbf57 100644 --- a/spring-mvc-xml/.project +++ b/spring-security-client/spring-security-mvc/.project @@ -1,10 +1,15 @@ - spring-mvc-xml + spring-security-mvc + + org.eclipse.wst.jsdt.core.javascriptValidator + + + org.eclipse.jdt.core.javabuilder @@ -16,7 +21,7 @@ - org.eclipse.wst.validation.validationbuilder + org.eclipse.m2e.core.maven2Builder @@ -26,15 +31,15 @@ - org.eclipse.m2e.core.maven2Builder + org.eclipse.wst.validation.validationbuilder - org.springframework.ide.eclipse.core.springnature org.eclipse.jem.workbench.JavaEMFNature org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature org.eclipse.wst.common.project.facet.core.nature diff --git a/spring-security-client/spring-security-mvc/pom.xml b/spring-security-client/spring-security-mvc/pom.xml new file mode 100644 index 0000000000..ec3b1f1782 --- /dev/null +++ b/spring-security-client/spring-security-mvc/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + com.baeldung + spring-security-mvc + 0.0.1-SNAPSHOT + war + + spring-security-mvc + Spring Security MVC + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..4057a85f13 --- /dev/null +++ b/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.web.SpringBootServletInitializer; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-mvc/src/main/resources/application.properties b/spring-security-client/spring-security-mvc/src/main/resources/application.properties new file mode 100644 index 0000000000..c2eee0d931 --- /dev/null +++ b/spring-security-client/spring-security-mvc/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port: 8081 \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/.classpath b/spring-security-client/spring-security-thymeleaf-authentication/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-client/spring-security-thymeleaf-authentication/.project b/spring-security-client/spring-security-thymeleaf-authentication/.project new file mode 100644 index 0000000000..c6b921b16c --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/.project @@ -0,0 +1,48 @@ + + + spring-security-thymeleaf-authentication + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml new file mode 100644 index 0000000000..cdbe0946f4 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + com.baeldung + spring-security-thymeleaf-authentication + 0.0.1-SNAPSHOT + war + + spring-security-thymeleaf-authentication + Spring Security thymeleaf authentication tag sample + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..bea0194b40 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,13 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..9ade60e54c --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/application.properties b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/application.properties new file mode 100644 index 0000000000..bafddced85 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8081 \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/index.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/index.html new file mode 100644 index 0000000000..c65b5f092b --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/index.html @@ -0,0 +1,23 @@ + + + + +Spring Security Thymeleaf + + + + + +
+ Current user name: Bob +
+ Current user roles: [ROLE_USER, ROLE_ADMIN] +
+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/.classpath b/spring-security-client/spring-security-thymeleaf-authorize/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-client/spring-security-thymeleaf-authorize/.project b/spring-security-client/spring-security-thymeleaf-authorize/.project new file mode 100644 index 0000000000..b722d4072d --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/.project @@ -0,0 +1,48 @@ + + + spring-security-thymeleaf-authorize + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml new file mode 100644 index 0000000000..5254f1db1a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + com.baeldung + spring-security-thymeleaf-authorize + 0.0.1-SNAPSHOT + war + + spring-security-thymeleaf-authorize + Spring Security thymeleaf authorize tag sample + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..bea0194b40 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,13 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..9ade60e54c --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/application.properties b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/application.properties new file mode 100644 index 0000000000..bafddced85 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8081 \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/templates/index.html b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/templates/index.html new file mode 100644 index 0000000000..fcbbfb4957 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/templates/index.html @@ -0,0 +1,32 @@ + + + + +Spring Security Thymeleaf + + + + + +
+
+ Only admins can see this message +
+ +
+ Only users can see this message +
+
+ +
+ Only users who can call "/admin" URL can see this message +
+
+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/.classpath b/spring-security-client/spring-security-thymeleaf-config/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-client/spring-security-thymeleaf-config/.project b/spring-security-client/spring-security-thymeleaf-config/.project new file mode 100644 index 0000000000..f1e44573c4 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/.project @@ -0,0 +1,48 @@ + + + spring-security-thymeleaf-config + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-client/spring-security-thymeleaf-config/pom.xml b/spring-security-client/spring-security-thymeleaf-config/pom.xml new file mode 100644 index 0000000000..ec145a29c8 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + com.baeldung + spring-security-thymeleaf-config + 0.0.1-SNAPSHOT + war + + spring-security-thymeleaf-config + Spring Security thymeleaf configuration sample project + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..bea0194b40 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,13 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..9ade60e54c --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/resources/application.properties b/spring-security-client/spring-security-thymeleaf-config/src/main/resources/application.properties new file mode 100644 index 0000000000..bafddced85 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8081 \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/resources/templates/index.html b/spring-security-client/spring-security-thymeleaf-config/src/main/resources/templates/index.html new file mode 100644 index 0000000000..8e7394ad6a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/resources/templates/index.html @@ -0,0 +1,21 @@ + + + + +Spring Security Thymeleaf + + + + + +
+ Welcome +
+ + \ No newline at end of file diff --git a/spring-security-custom-permission/.classpath b/spring-security-custom-permission/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-custom-permission/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-custom-permission/.project b/spring-security-custom-permission/.project new file mode 100644 index 0000000000..06b5975e98 --- /dev/null +++ b/spring-security-custom-permission/.project @@ -0,0 +1,48 @@ + + + spring-security-custom-permission + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-custom-permission/pom.xml b/spring-security-custom-permission/pom.xml new file mode 100644 index 0000000000..6f460f1751 --- /dev/null +++ b/spring-security-custom-permission/pom.xml @@ -0,0 +1,107 @@ + + + 4.0.0 + + com.baeldung + spring-security-custom-permission + 0.0.1-SNAPSHOT + war + + spring-security-custom-permission + Spring Security custom permission + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + + + + + + junit + junit + test + + + + org.hamcrest + hamcrest-core + test + + + + org.hamcrest + hamcrest-library + test + + + + com.jayway.restassured + rest-assured + ${rest-assured.version} + test + + + commons-logging + commons-logging + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + 2.4.0 + + + diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/Application.java b/spring-security-custom-permission/src/main/java/org/baeldung/Application.java new file mode 100644 index 0000000000..a9d6f3b8b1 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/Application.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/MethodSecurityConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/MethodSecurityConfig.java new file mode 100644 index 0000000000..c4624e85e0 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/MethodSecurityConfig.java @@ -0,0 +1,21 @@ +package org.baeldung.config; + +import org.baeldung.security.CustomMethodSecurityExpressionHandler; +import org.baeldung.security.CustomPermissionEvaluator; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; + +@Configuration +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { + + @Override + protected MethodSecurityExpressionHandler createExpressionHandler() { + // final DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); + final CustomMethodSecurityExpressionHandler expressionHandler = new CustomMethodSecurityExpressionHandler(); + expressionHandler.setPermissionEvaluator(new CustomPermissionEvaluator()); + return expressionHandler; + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..9ade60e54c --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } +} \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..b365744bea --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,43 @@ +package org.baeldung.config; + +import org.baeldung.security.MyUserDetailsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +@ComponentScan("org.baeldung.security") +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private MyUserDetailsService userDetailsService; + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService); + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + .and().csrf().disable(); + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java new file mode 100644 index 0000000000..47616ca61a --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java @@ -0,0 +1,70 @@ +package org.baeldung.persistence; + +import java.util.Arrays; +import java.util.HashSet; + +import javax.annotation.PostConstruct; + +import org.baeldung.persistence.dao.OrganizationRepository; +import org.baeldung.persistence.dao.PrivilegeRepository; +import org.baeldung.persistence.dao.UserRepository; +import org.baeldung.persistence.model.Organization; +import org.baeldung.persistence.model.Privilege; +import org.baeldung.persistence.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class SetupData { + @Autowired + private UserRepository userRepository; + + @Autowired + private PrivilegeRepository privilegeRepository; + + @Autowired + private OrganizationRepository organizationRepository; + + @PostConstruct + public void init() { + initPrivileges(); + initOrganizations(); + initUsers(); + } + + private void initUsers() { + final Privilege privilege1 = privilegeRepository.findByName("FOO_READ_PRIVILEGE"); + final Privilege privilege2 = privilegeRepository.findByName("FOO_WRITE_PRIVILEGE"); + // + final User user1 = new User(); + user1.setUsername("john"); + user1.setPassword("123"); + user1.setPrivileges(new HashSet(Arrays.asList(privilege1))); + user1.setOrganization(organizationRepository.findByName("FirstOrg")); + userRepository.save(user1); + // + final User user2 = new User(); + user2.setUsername("tom"); + user2.setPassword("111"); + user2.setPrivileges(new HashSet(Arrays.asList(privilege1, privilege2))); + user2.setOrganization(organizationRepository.findByName("SecondOrg")); + userRepository.save(user2); + } + + private void initOrganizations() { + final Organization org1 = new Organization("FirstOrg"); + organizationRepository.save(org1); + // + final Organization org2 = new Organization("SecondOrg"); + organizationRepository.save(org2); + + } + + private void initPrivileges() { + final Privilege privilege1 = new Privilege("FOO_READ_PRIVILEGE"); + privilegeRepository.save(privilege1); + // + final Privilege privilege2 = new Privilege("FOO_WRITE_PRIVILEGE"); + privilegeRepository.save(privilege2); + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/OrganizationRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/OrganizationRepository.java new file mode 100644 index 0000000000..a20d24057b --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/OrganizationRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.Organization; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface OrganizationRepository extends JpaRepository { + + public Organization findByName(String name); + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java new file mode 100644 index 0000000000..edf9002c3d --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.Privilege; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PrivilegeRepository extends JpaRepository { + + public Privilege findByName(String name); + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java new file mode 100644 index 0000000000..679dd6c363 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { + + User findByUsername(final String username); + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Foo.java new file mode 100644 index 0000000000..29c19cf22e --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Foo.java @@ -0,0 +1,94 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Foo { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false) + private String name; + + // + + public Foo() { + super(); + } + + public Foo(String name) { + super(); + this.name = name; + } + + // + + 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; + } + + // + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((id == null) ? 0 : id.hashCode()); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Foo other = (Foo) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Organization.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Organization.java new file mode 100644 index 0000000000..645285b5e9 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Organization.java @@ -0,0 +1,95 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Organization { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false, unique = true) + private String name; + + // + + public Organization() { + super(); + } + + public Organization(String name) { + super(); + this.name = name; + } + + // + + 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; + } + + // + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Organization [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((id == null) ? 0 : id.hashCode()); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Organization other = (Organization) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Privilege.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Privilege.java new file mode 100644 index 0000000000..ff3ae62c25 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Privilege.java @@ -0,0 +1,95 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Privilege { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false, unique = true) + private String name; + + // + + public Privilege() { + super(); + } + + public Privilege(String name) { + super(); + this.name = name; + } + + // + + 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; + } + + // + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Privilege [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((id == null) ? 0 : id.hashCode()); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Privilege other = (Privilege) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java new file mode 100644 index 0000000000..86b81cdcee --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java @@ -0,0 +1,195 @@ +package org.baeldung.persistence.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +@Entity +public class User implements UserDetails { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false, unique = true) + private String username; + + private String password; + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "users_privileges", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id")) + private Set privileges; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "organization_id", referencedColumnName = "id") + private Organization organization; + + // + + public User() { + super(); + } + + // + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + @Override + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @Override + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Set getPrivileges() { + return privileges; + } + + public void setPrivileges(Set privileges) { + this.privileges = privileges; + } + + public Organization getOrganization() { + return organization; + } + + public void setOrganization(Organization organization) { + this.organization = organization; + } + + // + + @Override + public Collection getAuthorities() { + final List authorities = new ArrayList(); + for (final Privilege privilege : this.getPrivileges()) { + authorities.add(new SimpleGrantedAuthority(privilege.getName())); + } + return authorities; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + // + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append(", privileges=").append(privileges).append(", organization=").append(organization).append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((id == null) ? 0 : id.hashCode()); + result = (prime * result) + ((organization == null) ? 0 : organization.hashCode()); + result = (prime * result) + ((password == null) ? 0 : password.hashCode()); + result = (prime * result) + ((privileges == null) ? 0 : privileges.hashCode()); + result = (prime * result) + ((username == null) ? 0 : username.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final User other = (User) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (organization == null) { + if (other.organization != null) { + return false; + } + } else if (!organization.equals(other.organization)) { + return false; + } + if (password == null) { + if (other.password != null) { + return false; + } + } else if (!password.equals(other.password)) { + return false; + } + if (privileges == null) { + if (other.privileges != null) { + return false; + } + } else if (!privileges.equals(other.privileges)) { + return false; + } + if (username == null) { + if (other.username != null) { + return false; + } + } else if (!username.equals(other.username)) { + return false; + } + return true; + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionHandler.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionHandler.java new file mode 100644 index 0000000000..e040a0b109 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionHandler.java @@ -0,0 +1,22 @@ +package org.baeldung.security; + +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; +import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; +import org.springframework.security.authentication.AuthenticationTrustResolver; +import org.springframework.security.authentication.AuthenticationTrustResolverImpl; +import org.springframework.security.core.Authentication; + +public class CustomMethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler { + private final AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl(); + + @Override + protected MethodSecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, MethodInvocation invocation) { + // final CustomMethodSecurityExpressionRoot root = new CustomMethodSecurityExpressionRoot(authentication); + final MySecurityExpressionRoot root = new MySecurityExpressionRoot(authentication); + root.setPermissionEvaluator(getPermissionEvaluator()); + root.setTrustResolver(this.trustResolver); + root.setRoleHierarchy(getRoleHierarchy()); + return root; + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java new file mode 100644 index 0000000000..a3f4644592 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java @@ -0,0 +1,50 @@ +package org.baeldung.security; + +import org.baeldung.persistence.model.User; +import org.springframework.security.access.expression.SecurityExpressionRoot; +import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; +import org.springframework.security.core.Authentication; + +public class CustomMethodSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations { + + private Object filterObject; + private Object returnObject; + + public CustomMethodSecurityExpressionRoot(Authentication authentication) { + super(authentication); + } + + // + public boolean isMember(Long OrganizationId) { + final User user = (User) this.getPrincipal(); + return user.getOrganization().getId().longValue() == OrganizationId.longValue(); + } + + // + + @Override + public Object getFilterObject() { + return this.filterObject; + } + + @Override + public Object getReturnObject() { + return this.returnObject; + } + + @Override + public Object getThis() { + return this; + } + + @Override + public void setFilterObject(Object obj) { + this.filterObject = obj; + } + + @Override + public void setReturnObject(Object obj) { + this.returnObject = obj; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java new file mode 100644 index 0000000000..e81f9f8939 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java @@ -0,0 +1,47 @@ +package org.baeldung.security; + +import java.io.Serializable; + +import org.springframework.security.access.PermissionEvaluator; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; + +public class CustomPermissionEvaluator implements PermissionEvaluator { + + @Override + public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) { + System.out.println(auth); + if ((auth == null) || (targetDomainObject == null) || !(permission instanceof String)) { + return false; + } + String targetType = ""; + if (targetDomainObject instanceof String) { + targetType = targetDomainObject.toString().toUpperCase(); + } else { + targetType = targetDomainObject.getClass().getSimpleName().toUpperCase(); + System.out.println(targetType); + } + return hasPrivilege(auth, targetType, permission.toString().toUpperCase()); + } + + @Override + public boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) { + if ((auth == null) || (targetType == null) || !(permission instanceof String)) { + return false; + } + return hasPrivilege(auth, targetType.toUpperCase(), permission.toString().toUpperCase()); + } + + private boolean hasPrivilege(Authentication auth, String targetType, String permission) { + for (final GrantedAuthority grantedAuth : auth.getAuthorities()) { + System.out.println("here " + grantedAuth); + if (grantedAuth.getAuthority().startsWith(targetType)) { + if (grantedAuth.getAuthority().contains(permission)) { + return true; + } + } + } + return false; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java new file mode 100644 index 0000000000..a09d166798 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java @@ -0,0 +1,203 @@ +package org.baeldung.security; + +import java.io.Serializable; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import org.baeldung.persistence.model.User; +import org.springframework.security.access.PermissionEvaluator; +import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; +import org.springframework.security.access.hierarchicalroles.RoleHierarchy; +import org.springframework.security.authentication.AuthenticationTrustResolver; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.AuthorityUtils; + +public class MySecurityExpressionRoot implements MethodSecurityExpressionOperations { + protected final Authentication authentication; + private AuthenticationTrustResolver trustResolver; + private RoleHierarchy roleHierarchy; + private Set roles; + private String defaultRolePrefix = "ROLE_"; + + public final boolean permitAll = true; + public final boolean denyAll = false; + private PermissionEvaluator permissionEvaluator; + public final String read = "read"; + public final String write = "write"; + public final String create = "create"; + public final String delete = "delete"; + public final String admin = "administration"; + + // + + private Object filterObject; + private Object returnObject; + + public MySecurityExpressionRoot(Authentication authentication) { + if (authentication == null) { + throw new IllegalArgumentException("Authentication object cannot be null"); + } + this.authentication = authentication; + } + + @Override + public final boolean hasAuthority(String authority) { + throw new RuntimeException("method hasAuthority() not allowed"); + } + + @Override + public final boolean hasAnyAuthority(String... authorities) { + return hasAnyAuthorityName(null, authorities); + } + + @Override + public final boolean hasRole(String role) { + return hasAnyRole(role); + } + + @Override + public final boolean hasAnyRole(String... roles) { + return hasAnyAuthorityName(defaultRolePrefix, roles); + } + + private boolean hasAnyAuthorityName(String prefix, String... roles) { + final Set roleSet = getAuthoritySet(); + + for (final String role : roles) { + final String defaultedRole = getRoleWithDefaultPrefix(prefix, role); + if (roleSet.contains(defaultedRole)) { + return true; + } + } + + return false; + } + + @Override + public final Authentication getAuthentication() { + return authentication; + } + + @Override + public final boolean permitAll() { + return true; + } + + @Override + public final boolean denyAll() { + return false; + } + + @Override + public final boolean isAnonymous() { + return trustResolver.isAnonymous(authentication); + } + + @Override + public final boolean isAuthenticated() { + return !isAnonymous(); + } + + @Override + public final boolean isRememberMe() { + return trustResolver.isRememberMe(authentication); + } + + @Override + public final boolean isFullyAuthenticated() { + return !trustResolver.isAnonymous(authentication) && !trustResolver.isRememberMe(authentication); + } + + public Object getPrincipal() { + return authentication.getPrincipal(); + } + + public void setTrustResolver(AuthenticationTrustResolver trustResolver) { + this.trustResolver = trustResolver; + } + + public void setRoleHierarchy(RoleHierarchy roleHierarchy) { + this.roleHierarchy = roleHierarchy; + } + + public void setDefaultRolePrefix(String defaultRolePrefix) { + this.defaultRolePrefix = defaultRolePrefix; + } + + private Set getAuthoritySet() { + if (roles == null) { + roles = new HashSet(); + Collection userAuthorities = authentication.getAuthorities(); + + if (roleHierarchy != null) { + userAuthorities = roleHierarchy.getReachableGrantedAuthorities(userAuthorities); + } + + roles = AuthorityUtils.authorityListToSet(userAuthorities); + } + + return roles; + } + + @Override + public boolean hasPermission(Object target, Object permission) { + return permissionEvaluator.hasPermission(authentication, target, permission); + } + + @Override + public boolean hasPermission(Object targetId, String targetType, Object permission) { + return permissionEvaluator.hasPermission(authentication, (Serializable) targetId, targetType, permission); + } + + public void setPermissionEvaluator(PermissionEvaluator permissionEvaluator) { + this.permissionEvaluator = permissionEvaluator; + } + + private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) { + if (role == null) { + return role; + } + if ((defaultRolePrefix == null) || (defaultRolePrefix.length() == 0)) { + return role; + } + if (role.startsWith(defaultRolePrefix)) { + return role; + } + return defaultRolePrefix + role; + } + + // + public boolean isMember(Long OrganizationId) { + final User user = (User) this.getPrincipal(); + return user.getOrganization().getId().longValue() == OrganizationId.longValue(); + } + + // + + @Override + public Object getFilterObject() { + return this.filterObject; + } + + @Override + public Object getReturnObject() { + return this.returnObject; + } + + @Override + public Object getThis() { + return this; + } + + @Override + public void setFilterObject(Object obj) { + this.filterObject = obj; + } + + @Override + public void setReturnObject(Object obj) { + this.returnObject = obj; + } +} \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java new file mode 100644 index 0000000000..19276a906e --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -0,0 +1,31 @@ +package org.baeldung.security; + +import org.baeldung.persistence.dao.UserRepository; +import org.baeldung.persistence.model.User; +import org.springframework.beans.factory.annotation.Autowired; +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 +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + private UserRepository userRepository; + + public MyUserDetailsService() { + super(); + } + + // API + + @Override + public UserDetails loadUserByUsername(final String username) { + final User user = userRepository.findByUsername(username); + if (user == null) { + throw new UsernameNotFoundException(username); + } + return user; + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java b/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java new file mode 100644 index 0000000000..7e279907c6 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java @@ -0,0 +1,57 @@ +package org.baeldung.web; + +import org.baeldung.persistence.dao.OrganizationRepository; +import org.baeldung.persistence.model.Foo; +import org.baeldung.persistence.model.Organization; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +@Controller +public class MainController { + + @Autowired + private OrganizationRepository organizationRepository; + + @PreAuthorize("hasPermission('Foo', 'read')") + @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") + @ResponseBody + public Foo findById(@PathVariable final long id) { + return new Foo("Sample"); + } + + @PreAuthorize("hasPermission(#foo, 'write')") + @RequestMapping(method = RequestMethod.POST, value = "/foos") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo create(@RequestBody final Foo foo) { + return foo; + } + + // + + @PreAuthorize("hasAuthority('FOO_READ_PRIVILEGE')") + @RequestMapping(method = RequestMethod.GET, value = "/foos") + @ResponseBody + public Foo findFooByName(@RequestParam final String name) { + return new Foo(name); + } + + // + + @PreAuthorize("isMember(#id)") + @RequestMapping(method = RequestMethod.GET, value = "/organizations/{id}") + @ResponseBody + public Organization findOrgById(@PathVariable final long id) { + return organizationRepository.findOne(id); + } + +} diff --git a/spring-security-custom-permission/src/main/resources/application.properties b/spring-security-custom-permission/src/main/resources/application.properties new file mode 100644 index 0000000000..0b40f62fa9 --- /dev/null +++ b/spring-security-custom-permission/src/main/resources/application.properties @@ -0,0 +1,9 @@ +server.port=8081 +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1 +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.database=H2 +spring.jpa.show-sql=false +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/resources/templates/index.html b/spring-security-custom-permission/src/main/resources/templates/index.html new file mode 100644 index 0000000000..8e7394ad6a --- /dev/null +++ b/spring-security-custom-permission/src/main/resources/templates/index.html @@ -0,0 +1,21 @@ + + + + +Spring Security Thymeleaf + + + + + +
+ Welcome +
+ + \ No newline at end of file diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java new file mode 100644 index 0000000000..80b1390083 --- /dev/null +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java @@ -0,0 +1,67 @@ +package org.baeldung.web; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.baeldung.persistence.model.Foo; +import org.junit.Test; +import org.springframework.http.MediaType; + +import com.jayway.restassured.RestAssured; +import com.jayway.restassured.authentication.FormAuthConfig; +import com.jayway.restassured.response.Response; +import com.jayway.restassured.specification.RequestSpecification; + +public class LiveTest { + + private final FormAuthConfig formAuthConfig = new FormAuthConfig("http://localhost:8081/login", "username", "password"); + + @Test + public void givenUserWithReadPrivilegeAndHasPermission_whenGetFooById_thenOK() { + final Response response = givenAuth("john", "123").get("http://localhost:8081/foos/1"); + assertEquals(200, response.getStatusCode()); + assertTrue(response.asString().contains("id")); + } + + @Test + public void givenUserWithNoWritePrivilegeAndHasPermission_whenPostFoo_thenForbidden() { + final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8081/foos"); + assertEquals(403, response.getStatusCode()); + } + + @Test + public void givenUserWithWritePrivilegeAndHasPermission_whenPostFoo_thenOk() { + final Response response = givenAuth("tom", "111").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8081/foos"); + assertEquals(201, response.getStatusCode()); + assertTrue(response.asString().contains("id")); + } + + // + + @Test + public void givenUserMemberInOrganization_whenGetOrganization_thenOK() { + final Response response = givenAuth("john", "123").get("http://localhost:8081/organizations/1"); + assertEquals(200, response.getStatusCode()); + assertTrue(response.asString().contains("id")); + } + + @Test + public void givenUserMemberNotInOrganization_whenGetOrganization_thenForbidden() { + final Response response = givenAuth("john", "123").get("http://localhost:8081/organizations/2"); + assertEquals(403, response.getStatusCode()); + } + + // + + @Test + public void givenDisabledSecurityExpression_whenGetFooByName_thenError() { + final Response response = givenAuth("john", "123").get("http://localhost:8081/foos?name=sample"); + assertEquals(500, response.getStatusCode()); + assertTrue(response.asString().contains("method hasAuthority() not allowed")); + } + + // + private RequestSpecification givenAuth(String username, String password) { + return RestAssured.given().auth().form(username, password, formAuthConfig); + } +} \ No newline at end of file diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 4da114c78b..08cb09384b 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -1,14 +1,59 @@ package org.baeldung.spring; +import org.baeldung.security.CustomLogoutSuccessHandler; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; +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.web.authentication.logout.LogoutSuccessHandler; @Configuration -@ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecSecurityConfig { +// @ImportResource({ "classpath:webSecurityConfig.xml" }) +@EnableWebSecurity +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public SecSecurityConfig() { super(); } + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("user1").password("user1Pass").roles("USER") + .and() + .withUser("user2").password("user2Pass").roles("USER"); + // @formatter:on + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/anonymous*").anonymous() + .antMatchers("/login*").permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/perform_login") + .defaultSuccessUrl("/homepage.html",true) + .failureUrl("/login.html?error=true") + .and() + .logout() + .logoutUrl("/perform_logout") + .deleteCookies("JSESSIONID") + .logoutSuccessHandler(logoutSuccessHandler()); + // @formatter:on + } + + @Bean + public LogoutSuccessHandler logoutSuccessHandler() { + return new CustomLogoutSuccessHandler(); + } + } diff --git a/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml b/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml index f13ae48c7e..0a0a340995 100644 --- a/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml @@ -1,9 +1,8 @@ - + Spring MVC Application diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 19f1ca76a6..19f49ea59d 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -21,7 +21,7 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - protected MySimpleUrlAuthenticationSuccessHandler() { + public MySimpleUrlAuthenticationSuccessHandler() { super(); } diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 4da114c78b..deeea78e4e 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -1,14 +1,72 @@ package org.baeldung.spring; +import org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; +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.config.http.SessionCreationPolicy; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import org.springframework.security.web.session.HttpSessionEventPublisher; @Configuration -@ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecSecurityConfig { +// @ImportResource({ "classpath:webSecurityConfig.xml" }) +@EnableWebSecurity +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public SecSecurityConfig() { super(); } + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("user1").password("user1Pass").roles("USER") + .and() + .withUser("admin1").password("admin1Pass").roles("ADMIN"); + // @formatter:on + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/anonymous*").anonymous() + .antMatchers("/login*").permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/login") + .successHandler(successHandler()) + .failureUrl("/login.html?error=true") + .and() + .logout().deleteCookies("JSESSIONID") + .and() + .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400) + .and() + .sessionManagement() + .sessionFixation().migrateSession() + .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) + .invalidSessionUrl("/invalidSession.html") + .maximumSessions(2) + .expiredUrl("/sessionExpired.html"); + + // @formatter:on + } + + private AuthenticationSuccessHandler successHandler() { + return new MySimpleUrlAuthenticationSuccessHandler(); + } + + @Bean + public HttpSessionEventPublisher httpSessionEventPublisher() { + return new HttpSessionEventPublisher(); + } + } diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml b/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml index 45b49b2a91..57826fadac 100644 --- a/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml @@ -1,9 +1,8 @@ - + Spring MVC Session Application @@ -13,9 +12,9 @@ org.baeldung.web.SessionListenerWithMetrics - + diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java index ee9b0868e7..67d9abbae5 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java @@ -1,16 +1,41 @@ package org.baeldung.config.parent; +import org.baeldung.security.CustomAuthenticationProvider; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; +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; @Configuration -@ImportResource({ "classpath:webSecurityConfig.xml" }) +// @ImportResource({ "classpath:webSecurityConfig.xml" }) +@EnableWebSecurity @ComponentScan("org.baeldung.security") -public class SecurityConfig { +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private CustomAuthenticationProvider authProvider; public SecurityConfig() { super(); } + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(authProvider); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .authorizeRequests().anyRequest().authenticated() + .and() + .httpBasic(); + // @formatter:on + } + + } diff --git a/xstream/pom.xml b/xstream/pom.xml new file mode 100644 index 0000000000..8a5aec41e9 --- /dev/null +++ b/xstream/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + org.baeldung + xstream-introduction + 0.0.1-SNAPSHOT + xstream-introduction + An Introduction To XStream + + + + com.thoughtworks.xstream + xstream + 1.4.5 + + + + junit + junit + 4.12 + + + + log4j + log4j + 1.2.17 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + + \ No newline at end of file diff --git a/xstream/src/main/java/com/baeldung/annotation/pojo/Customer.java b/xstream/src/main/java/com/baeldung/annotation/pojo/Customer.java new file mode 100644 index 0000000000..2cdb0f56c9 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/annotation/pojo/Customer.java @@ -0,0 +1,46 @@ +package com.baeldung.annotation.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +import java.util.Date; + +@XStreamAlias("customer") +public class Customer { + + @XStreamAlias("fn") + private String firstName; + + private String lastName; + + private Date dob; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + + ", dob=" + dob + "]"; + } +} diff --git a/xstream/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java b/xstream/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java new file mode 100644 index 0000000000..f5b98c9c1b --- /dev/null +++ b/xstream/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java @@ -0,0 +1,50 @@ +package com.baeldung.annotation.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamOmitField; + +import java.util.Date; + + +@XStreamAlias("customer") +public class CustomerOmitField { + + @XStreamOmitField + private String firstName; + + private String lastName; + + private Date dob; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + @Override + public String toString() { + return "CustomerOmitAnnotation [firstName=" + firstName + ", lastName=" + + lastName + ", dob=" + dob + "]"; + } + + +} diff --git a/xstream/src/main/java/com/baeldung/complex/pojo/ContactDetails.java b/xstream/src/main/java/com/baeldung/complex/pojo/ContactDetails.java new file mode 100644 index 0000000000..e091492a1a --- /dev/null +++ b/xstream/src/main/java/com/baeldung/complex/pojo/ContactDetails.java @@ -0,0 +1,46 @@ +package com.baeldung.complex.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("ContactDetails") +public class ContactDetails { + + private String mobile; + + private String landline; + + @XStreamAsAttribute + private String contactType; + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getLandline() { + return landline; + } + + public void setLandline(String landline) { + this.landline = landline; + } + + public String getContactType() { + return contactType; + } + + public void setContactType(String contactType) { + this.contactType = contactType; + } + + @Override + public String toString() { + return "ContactDetails [mobile=" + mobile + ", landline=" + landline + + ", contactType=" + contactType + "]"; + } + +} diff --git a/xstream/src/main/java/com/baeldung/complex/pojo/Customer.java b/xstream/src/main/java/com/baeldung/complex/pojo/Customer.java new file mode 100644 index 0000000000..c6f98982f0 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/complex/pojo/Customer.java @@ -0,0 +1,57 @@ +package com.baeldung.complex.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +import java.util.Date; +import java.util.List; + +@XStreamAlias("customer") +public class Customer { + + private String firstName; + + private String lastName; + + private Date dob; + + private List contactDetailsList; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + public List getContactDetailsList() { + return contactDetailsList; + } + + public void setContactDetailsList(List contactDetailsList) { + this.contactDetailsList = contactDetailsList; + } + + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + + "]"; + } +} diff --git a/xstream/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java b/xstream/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java new file mode 100644 index 0000000000..38ec7ff077 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java @@ -0,0 +1,46 @@ +package com.baeldung.implicit.collection.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("ContactDetails") +public class ContactDetails { + + private String mobile; + + private String landline; + + @XStreamAsAttribute + private String contactType; + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getLandline() { + return landline; + } + + public void setLandline(String landline) { + this.landline = landline; + } + + public String getContactType() { + return contactType; + } + + public void setContactType(String contactType) { + this.contactType = contactType; + } + + @Override + public String toString() { + return "ContactDetails [mobile=" + mobile + ", landline=" + landline + + ", contactType=" + contactType + "]"; + } + +} diff --git a/xstream/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java b/xstream/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java new file mode 100644 index 0000000000..a50ac850dd --- /dev/null +++ b/xstream/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java @@ -0,0 +1,59 @@ +package com.baeldung.implicit.collection.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamImplicit; + +import java.util.Date; +import java.util.List; + +@XStreamAlias("customer") +public class Customer { + + private String firstName; + + private String lastName; + + private Date dob; + + @XStreamImplicit + private List contactDetailsList; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + public List getContactDetailsList() { + return contactDetailsList; + } + + public void setContactDetailsList(List contactDetailsList) { + this.contactDetailsList = contactDetailsList; + } + + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + + "]"; + } +} diff --git a/xstream/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java b/xstream/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java new file mode 100644 index 0000000000..5dec19d181 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java @@ -0,0 +1,19 @@ +package com.baeldung.initializer; + +import com.thoughtworks.xstream.XStream; + +public class SimpleXstreamInitializer { + + private XStream xtreamInstance; + + public XStream getXstreamInstance() { + if (xtreamInstance == null) { + synchronized (SimpleXstreamInitializer.class) { + if (xtreamInstance == null) { + xtreamInstance = new XStream(); + } + } + } + return xtreamInstance; + } +} \ No newline at end of file diff --git a/xstream/src/main/java/com/baeldung/pojo/AddressDetails.java b/xstream/src/main/java/com/baeldung/pojo/AddressDetails.java new file mode 100644 index 0000000000..53ba7e9a85 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/pojo/AddressDetails.java @@ -0,0 +1,40 @@ +package com.baeldung.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +import java.util.List; + +@XStreamAlias("AddressDetails") +public class AddressDetails { + + private String address; + + private String zipcode; + + private List contactDetails; + + public String getZipcode() { + return zipcode; + } + + public void setZipcode(String zipcode) { + this.zipcode = zipcode; + } + + public List getContactDetails() { + return contactDetails; + } + + public void setContactDetails(List contactDetails) { + this.contactDetails = contactDetails; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + +} diff --git a/xstream/src/main/java/com/baeldung/pojo/ContactDetails.java b/xstream/src/main/java/com/baeldung/pojo/ContactDetails.java new file mode 100644 index 0000000000..75408bdba8 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/pojo/ContactDetails.java @@ -0,0 +1,28 @@ +package com.baeldung.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("ContactDetails") +public class ContactDetails { + + private String mobile; + + private String landline; + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getLandline() { + return landline; + } + + public void setLandline(String landline) { + this.landline = landline; + } + +} diff --git a/xstream/src/main/java/com/baeldung/pojo/Customer.java b/xstream/src/main/java/com/baeldung/pojo/Customer.java new file mode 100644 index 0000000000..728939c356 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/pojo/Customer.java @@ -0,0 +1,57 @@ +package com.baeldung.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamImplicit; + +import java.util.Date; +import java.util.List; + +@XStreamAlias("customer") +public class Customer { + + private String firstName; + + private String lastName; + + private Date dob; + + @XStreamImplicit + private List contactDetailsList; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + public List getContactDetailsList() { + return contactDetailsList; + } + + public void setContactDetailsList(List contactDetailsList) { + this.contactDetailsList = contactDetailsList; + } + + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]"; + } +} diff --git a/xstream/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java b/xstream/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java new file mode 100644 index 0000000000..f203c9cce9 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java @@ -0,0 +1,50 @@ +package com.baeldung.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +import java.util.List; + +@XStreamAlias("CustomerAddressDetails") +public class CustomerAddressDetails { + + private List addressDetails; + + private String firstName; + + private String lastName; + + private int age; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + + public List getAddressDetails() { + return addressDetails; + } + + public void setAddressDetails(List addressDetails) { + this.addressDetails = addressDetails; + } +} diff --git a/xstream/src/main/java/com/baeldung/pojo/CustomerPortfolio.java b/xstream/src/main/java/com/baeldung/pojo/CustomerPortfolio.java new file mode 100644 index 0000000000..90722feb71 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/pojo/CustomerPortfolio.java @@ -0,0 +1,20 @@ +package com.baeldung.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +import java.util.List; + +@XStreamAlias("CustomerPortfolio") +public class CustomerPortfolio { + + private List customerAddressDetailsList; + + public List getCustomerAddressDetailsList() { + return customerAddressDetailsList; + } + + public void setCustomerAddressDetailsList(List customerAddressDetailsList) { + this.customerAddressDetailsList = customerAddressDetailsList; + } + +} diff --git a/xstream/src/main/java/com/baeldung/utility/MyDateConverter.java b/xstream/src/main/java/com/baeldung/utility/MyDateConverter.java new file mode 100644 index 0000000000..af7ca19aac --- /dev/null +++ b/xstream/src/main/java/com/baeldung/utility/MyDateConverter.java @@ -0,0 +1,40 @@ +package com.baeldung.utility; + +import com.thoughtworks.xstream.converters.ConversionException; +import com.thoughtworks.xstream.converters.Converter; +import com.thoughtworks.xstream.converters.MarshallingContext; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import com.thoughtworks.xstream.io.HierarchicalStreamWriter; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.GregorianCalendar; + +public class MyDateConverter implements Converter { + + private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); + + @Override + public boolean canConvert(Class clazz) { + return Date.class.isAssignableFrom(clazz); + } + + @Override + public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext arg2) { + Date date = (Date) value; + writer.setValue(formatter.format(date)); + } + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext arg1) { + GregorianCalendar calendar = new GregorianCalendar(); + try { + calendar.setTime(formatter.parse(reader.getValue())); + } catch (ParseException e) { + throw new ConversionException(e.getMessage(), e); + } + return calendar; + } +} diff --git a/xstream/src/main/java/com/baeldung/utility/MySingleValueConverter.java b/xstream/src/main/java/com/baeldung/utility/MySingleValueConverter.java new file mode 100644 index 0000000000..9b242f1c7c --- /dev/null +++ b/xstream/src/main/java/com/baeldung/utility/MySingleValueConverter.java @@ -0,0 +1,28 @@ +package com.baeldung.utility; + +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.converters.SingleValueConverter; + +import java.text.SimpleDateFormat; +import java.util.Date; + +public class MySingleValueConverter implements SingleValueConverter { + + @Override + public boolean canConvert(Class clazz) { + return Customer.class.isAssignableFrom(clazz); + } + + @Override + public Object fromString(String arg0) { + return null; + } + + @Override + public String toString(Object obj) { + SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); + Date date = ((Customer) obj).getDob(); + return ((Customer) obj).getFirstName() + "," + ((Customer) obj).getLastName() + "," + formatter.format(date); + } + +} diff --git a/xstream/src/main/java/com/baeldung/utility/SimpleDataGeneration.java b/xstream/src/main/java/com/baeldung/utility/SimpleDataGeneration.java new file mode 100644 index 0000000000..cf038bfd1b --- /dev/null +++ b/xstream/src/main/java/com/baeldung/utility/SimpleDataGeneration.java @@ -0,0 +1,37 @@ +package com.baeldung.utility; + +import com.baeldung.pojo.ContactDetails; +import com.baeldung.pojo.Customer; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +public class SimpleDataGeneration { + + public static Customer generateData() { + Customer customer = new Customer(); + Calendar cal = Calendar.getInstance(); + cal.set(1986, 01, 14); + customer.setDob(cal.getTime()); + customer.setFirstName("XStream"); + customer.setLastName("Java"); + + List contactDetailsList = new ArrayList(); + + ContactDetails contactDetails1 = new ContactDetails(); + contactDetails1.setLandline("0124-2460311"); + contactDetails1.setMobile("6673543265"); + + ContactDetails contactDetails2 = new ContactDetails(); + contactDetails2.setLandline("0120-223312"); + contactDetails2.setMobile("4676543565"); + + contactDetailsList.add(contactDetails1); + contactDetailsList.add(contactDetails2); + + customer.setContactDetailsList(contactDetailsList); + return customer; + } + +} diff --git a/xstream/src/main/resources/log4j.properties b/xstream/src/main/resources/log4j.properties new file mode 100644 index 0000000000..9cdafc6bdb --- /dev/null +++ b/xstream/src/main/resources/log4j.properties @@ -0,0 +1,16 @@ +# Root logger option +log4j.rootLogger=DEBUG, file + +# Redirect log messages to console +# log4j.appender.stdout=org.apache.log4j.ConsoleAppender +# log4j.appender.stdout.Target=System.out +# log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n + +# Redirect log messages to a log file, support file rolling. +log4j.appender.file=org.apache.log4j.RollingFileAppender +log4j.appender.file.File=D:\\Test\\xstream-application.log +log4j.appender.file.MaxFileSize=5MB +log4j.appender.file.MaxBackupIndex=10 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java new file mode 100644 index 0000000000..479500c4a0 --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java @@ -0,0 +1,38 @@ +package com.baeldung.pojo.test; + +import com.baeldung.complex.pojo.Customer; +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class ComplexXmlToObjectAnnotationTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field-complex.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getContactDetailsList()); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java new file mode 100644 index 0000000000..8c569aa11e --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java @@ -0,0 +1,42 @@ +package com.baeldung.pojo.test; + +import com.baeldung.complex.pojo.ContactDetails; +import com.baeldung.complex.pojo.Customer; +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class ComplexXmlToObjectAttributeCollectionTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field-complex.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getContactDetailsList()); + for (ContactDetails contactDetails : customer.getContactDetailsList()) { + Assert.assertNotNull(contactDetails.getContactType()); + } + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java new file mode 100644 index 0000000000..29ef7a5d64 --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java @@ -0,0 +1,39 @@ +package com.baeldung.pojo.test; + +import com.baeldung.implicit.collection.pojo.Customer; +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class ComplexXmlToObjectCollectionTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-implicit-collection.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getContactDetailsList()); + //System.out.println(customer); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java new file mode 100644 index 0000000000..8a4de3b70a --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java @@ -0,0 +1,37 @@ +package com.baeldung.pojo.test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class XmlToObjectAliasTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.alias("customer", Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java new file mode 100644 index 0000000000..4a7ff2f74a --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java @@ -0,0 +1,38 @@ +package com.baeldung.pojo.test; + +import com.baeldung.annotation.pojo.Customer; +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class XmlToObjectAnnotationTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getFirstName()); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java new file mode 100644 index 0000000000..3b1b8326ab --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java @@ -0,0 +1,39 @@ +package com.baeldung.pojo.test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class XmlToObjectFieldAliasTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.alias("customer", Customer.class); + xstream.aliasField("fn", Customer.class, "firstName"); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getFirstName()); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java new file mode 100644 index 0000000000..95a034b3e7 --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java @@ -0,0 +1,38 @@ +package com.baeldung.pojo.test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class XmlToObjectIgnoreFieldsTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.alias("customer", Customer.class); + xstream.ignoreUnknownElements(); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-ignore-field.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + //System.out.println(customer); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java new file mode 100644 index 0000000000..b6b64ce8da --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java @@ -0,0 +1,46 @@ +package com.baeldung.pojo.test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.Customer; +import com.baeldung.utility.SimpleDataGeneration; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class XmlToObjectTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void convertXmlToObjectFromString() { + Customer customer = SimpleDataGeneration.generateData(); + String dataXml = xstream.toXML(customer); + Customer convertedCustomer = (Customer) xstream.fromXML(dataXml); + Assert.assertNotNull(convertedCustomer); + } + + +} diff --git a/xstream/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java b/xstream/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java new file mode 100644 index 0000000000..83a965ce1b --- /dev/null +++ b/xstream/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java @@ -0,0 +1,57 @@ +package com.baeldung.utility; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.AddressDetails; +import com.baeldung.pojo.ContactDetails; +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class XStreamSimpleXmlTest { + + private Customer customer; + private String dataXml; + private XStream xstream; + + @Before + public void dataSetup() { + customer = SimpleDataGeneration.generateData(); + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + xstream.processAnnotations(AddressDetails.class); + xstream.processAnnotations(ContactDetails.class); + xstream.omitField(Customer.class, "lastName"); + xstream.registerConverter(new MyDateConverter()); + // xstream.registerConverter(new MySingleValueConverter()); + xstream.aliasField("fn", Customer.class, "firstName"); + dataXml = xstream.toXML(customer); + } + + @Test + public void testClassAliasedAnnotation() { + Assert.assertNotEquals(-1, dataXml.indexOf("")); + } + + @Test + public void testFieldAliasedAnnotation() { + Assert.assertNotEquals(-1, dataXml.indexOf("")); + } + + @Test + public void testImplicitCollection() { + Assert.assertEquals(-1, dataXml.indexOf("contactDetailsList")); + } + + @Test + public void testDateFieldFormating() { + Assert.assertEquals("14-02-1986", dataXml.substring(dataXml.indexOf("") + 5, dataXml.indexOf(""))); + } + + @Test + public void testOmitField() { + Assert.assertEquals(-1, dataXml.indexOf("lastName")); + } +} diff --git a/xstream/src/test/resources/data-file-alias-field-complex.xml b/xstream/src/test/resources/data-file-alias-field-complex.xml new file mode 100644 index 0000000000..06050cd1ed --- /dev/null +++ b/xstream/src/test/resources/data-file-alias-field-complex.xml @@ -0,0 +1,15 @@ + + XStream + Java + 1986-02-14 04:14:05.874 UTC + + + 6673543265 + 0124-2460311 + + + 4676543565 + 0120-223312 + + + \ No newline at end of file diff --git a/xstream/src/test/resources/data-file-alias-field.xml b/xstream/src/test/resources/data-file-alias-field.xml new file mode 100644 index 0000000000..7e71d721ca --- /dev/null +++ b/xstream/src/test/resources/data-file-alias-field.xml @@ -0,0 +1,5 @@ + + XStream + Java + 1986-02-14 03:46:16.381 UTC + \ No newline at end of file diff --git a/xstream/src/test/resources/data-file-alias-implicit-collection.xml b/xstream/src/test/resources/data-file-alias-implicit-collection.xml new file mode 100644 index 0000000000..0cb852fc04 --- /dev/null +++ b/xstream/src/test/resources/data-file-alias-implicit-collection.xml @@ -0,0 +1,13 @@ + + XStream + Java + 1986-02-14 04:14:20.541 UTC + + 6673543265 + 0124-2460311 + + + 4676543565 + 0120-223312 + + \ No newline at end of file diff --git a/xstream/src/test/resources/data-file-alias.xml b/xstream/src/test/resources/data-file-alias.xml new file mode 100644 index 0000000000..61ee9f1ac3 --- /dev/null +++ b/xstream/src/test/resources/data-file-alias.xml @@ -0,0 +1,5 @@ + + XStream + Java + 1986-02-14 03:46:16.381 UTC + \ No newline at end of file diff --git a/xstream/src/test/resources/data-file-ignore-field.xml b/xstream/src/test/resources/data-file-ignore-field.xml new file mode 100644 index 0000000000..7dc8023b96 --- /dev/null +++ b/xstream/src/test/resources/data-file-ignore-field.xml @@ -0,0 +1,6 @@ + + XStream + Java + 1986-02-14 04:14:20.541 UTC + XStream Java + \ No newline at end of file diff --git a/xstream/src/test/resources/data-file.xml b/xstream/src/test/resources/data-file.xml new file mode 100644 index 0000000000..b8dbce32c0 --- /dev/null +++ b/xstream/src/test/resources/data-file.xml @@ -0,0 +1,5 @@ + + XStream + Java + 1986-02-14 03:46:16.381 UTC + \ No newline at end of file