Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
167187f732
|
@ -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();
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
|
|
|
@ -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<String> 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();
|
||||
}
|
||||
}
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1 @@
|
|||
Hello World!
|
|
@ -0,0 +1 @@
|
|||
Hello World!
|
|
@ -0,0 +1 @@
|
|||
My Name is John
|
|
@ -0,0 +1 @@
|
|||
My Name is Tom
|
|
@ -0,0 +1 @@
|
|||
My Name is Jane
|
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -60,7 +60,7 @@
|
|||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.module</groupId>
|
||||
<artifactId>jackson-module-jsonSchema</artifactId>
|
||||
<version>2.6.0</version>
|
||||
<version>2.7.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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"));
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -6,29 +6,28 @@
|
|||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
|
@ -1,6 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>sprint-data-redis</name>
|
||||
<name>jooq-spring</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
|
@ -10,11 +10,6 @@
|
|||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.springframework.ide.eclipse.core.springbuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.m2e.core.maven2Builder</name>
|
||||
<arguments>
|
||||
|
@ -22,7 +17,6 @@
|
|||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.springframework.ide.eclipse.core.springnature</nature>
|
||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
||||
</natures>
|
|
@ -0,0 +1,153 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>jooq-spring</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<org.jooq.version>3.7.3</org.jooq.version>
|
||||
<com.h2database.version>1.4.191</com.h2database.version>
|
||||
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
|
||||
<org.slf4j.version>1.7.18</org.slf4j.version>
|
||||
<ch.qos.logback.version>1.1.3</ch.qos.logback.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- jOOQ -->
|
||||
<dependency>
|
||||
<groupId>org.jooq</groupId>
|
||||
<artifactId>jooq</artifactId>
|
||||
<version>${org.jooq.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Database Access -->
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${com.h2database.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-jdbc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Logging -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${ch.qos.logback.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Testing -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>initialize</phase>
|
||||
<goals>
|
||||
<goal>read-project-properties</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<files>
|
||||
<file>src/main/resources/intro_config.properties</file>
|
||||
</files>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>sql-maven-plugin</artifactId>
|
||||
<version>1.5</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>initialize</phase>
|
||||
<goals>
|
||||
<goal>execute</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<driver>${db.driver}</driver>
|
||||
<url>${db.url}</url>
|
||||
<username>${db.username}</username>
|
||||
<password>${db.password}</password>
|
||||
<srcFiles>
|
||||
<srcFile>src/main/resources/intro_schema.sql</srcFile>
|
||||
</srcFiles>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${com.h2database.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.jooq</groupId>
|
||||
<artifactId>jooq-codegen-maven</artifactId>
|
||||
<version>${org.jooq.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>generate</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<jdbc>
|
||||
<driver>${db.driver}</driver>
|
||||
<url>${db.url}</url>
|
||||
<user>${db.username}</user>
|
||||
<password>${db.password}</password>
|
||||
</jdbc>
|
||||
<generator>
|
||||
<target>
|
||||
<packageName>com.baeldung.jooq.introduction.db</packageName>
|
||||
<directory>src/main/java</directory>
|
||||
</target>
|
||||
</generator>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -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
|
|
@ -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);
|
|
@ -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()));
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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<Record3<Integer, String, Integer>> 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<Record3<Integer, String, String>> 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<Record3<Integer, String, String>> 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();
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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<Article, String> {
|
||||
|
||||
Page<Article> findByAuthorsName(String name, Pageable pageable);
|
||||
|
||||
@Query("{\"bool\": {\"must\": [{\"match\": {\"authors.name\": \"?0\"}}]}}")
|
||||
Page<Article> findByAuthorsNameUsingCustomQuery(String name, Pageable pageable);
|
||||
}
|
|
@ -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<Author> 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) +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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<Article, String> {
|
||||
|
||||
Page<Article> findByAuthorsName(String name, Pageable pageable);
|
||||
|
|
|
@ -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<Article> 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<Article> 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<Article> 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<Article> 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<Article> 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<String, Aggregation> results = response.getAggregations().asMap();
|
||||
StringTerms topTags = (StringTerms) results.get("top_tags");
|
||||
|
||||
List<String> 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<String, Aggregation> results = response.getAggregations().asMap();
|
||||
StringTerms topTags = (StringTerms) results.get("top_tags");
|
||||
|
||||
List<String> 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<Article> 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<Article> 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<Article> articles = elasticsearchTemplate
|
||||
.queryForList(searchQuery, Article.class);
|
||||
assertEquals(2, articles.size());
|
||||
}
|
||||
}
|
|
@ -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<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||
assertEquals(1, articles.size());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,16 +1,15 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>sprint-data-redis</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<artifactId>spring-data-redis</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
||||
<spring.version>4.2.5.RELEASE</spring.version>
|
||||
|
||||
<spring-data-redis>1.6.2.RELEASE</spring-data-redis>
|
||||
<nosqlunit.version>0.8.0</nosqlunit.version>
|
||||
</properties>
|
||||
|
@ -72,7 +71,6 @@
|
|||
<artifactId>nosqlunit-redis</artifactId>
|
||||
<version>${nosqlunit.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -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<String, Object> redisTemplate() {
|
||||
final RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
|
||||
template.setConnectionFactory(jedisConnectionFactory());
|
||||
template.setValueSerializer(new GenericToStringSerializer<Object>(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");
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.spring.data.redis.model;
|
||||
package com.baeldung.spring.data.redis.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.spring.data.redis.queue;
|
||||
|
||||
|
||||
public interface MessagePublisher {
|
||||
|
||||
void publish(final String message);
|
||||
}
|
|
@ -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<String, Object> redisTemplate;
|
||||
@Autowired
|
||||
private ChannelTopic topic;
|
||||
|
||||
public RedisMessagePublisher() {
|
||||
}
|
||||
|
||||
public RedisMessagePublisher(final RedisTemplate<String, Object> redisTemplate,
|
||||
final ChannelTopic topic) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.topic = topic;
|
||||
}
|
||||
|
||||
public void publish(final String message) {
|
||||
redisTemplate.convertAndSend(topic.getTopic(), message);
|
||||
}
|
||||
}
|
|
@ -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<String> messageList = new ArrayList<String>();
|
||||
|
||||
public void onMessage(final Message message, final byte[] pattern) {
|
||||
messageList.add(message.toString());
|
||||
System.out.println("Message received: " + new String(message.getBody()));
|
||||
}
|
||||
}
|
|
@ -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);
|
|
@ -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;
|
|
@ -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<String, Object> redisTemplate() {
|
||||
final RedisTemplate< String, Object> template = new RedisTemplate<String, Object>();
|
||||
template.setConnectionFactory(jedisConnectionFactory());
|
||||
return template;
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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;
|
|
@ -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
|
|
@ -0,0 +1,63 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>intro-spring-data-rest</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>intro-spring-data-rest</name>
|
||||
<description>Intro to Spring Data REST</description>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.3.3.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-rest</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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<WebsiteUser, Long> {
|
||||
List<WebsiteUser> findByName(@Param("name") String name);
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -1,37 +1,37 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" output="target/classes" path="src/main/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="output" path="target/classes"/>
|
||||
</classpath>
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" output="target/classes" path="src/main/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="output" path="target/classes"/>
|
||||
</classpath>
|
||||
|
|
|
@ -57,6 +57,13 @@
|
|||
<artifactId>slf4j-log4j12</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<!-- common -->
|
||||
<dependency>
|
||||
<groupId>commons-fileupload</groupId>
|
||||
<artifactId>commons-fileupload</artifactId>
|
||||
<version>1.3.1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
|
|
|
@ -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() {
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.aop;
|
||||
package com.baeldung.aop;
|
||||
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
|
@ -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;
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.aop.annotations;
|
||||
package com.baeldung.aop.annotations;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.aop.annotations;
|
||||
package com.baeldung.aop.annotations;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
|
@ -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
|
|
@ -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;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.events;
|
||||
package com.baeldung.events;
|
||||
|
||||
import org.springframework.context.ApplicationEvent;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.events;
|
||||
package com.baeldung.events;
|
||||
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.stereotype.Component;
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.model;
|
||||
package com.baeldung.model;
|
||||
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
|
@ -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 {
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.model;
|
||||
package com.baeldung.model;
|
||||
|
||||
public class User {
|
||||
private String firstname;
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.processor;
|
||||
package com.baeldung.processor;
|
||||
|
||||
import org.thymeleaf.Arguments;
|
||||
import org.thymeleaf.dom.Element;
|
|
@ -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<IDialect> 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/");
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -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<String> 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");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.web;
|
||||
package com.baeldung.web;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.web;
|
||||
package com.baeldung.web;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
|
@ -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()) {
|
|
@ -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";
|
||||
}
|
||||
}
|
|
@ -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;
|
|
@ -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<IDialect> 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/");
|
||||
}
|
||||
|
||||
}
|
|
@ -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<String> 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");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -7,8 +7,8 @@
|
|||
http://www.springframework.org/schema/aop
|
||||
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
|
||||
|
||||
<bean id="perfomanceMeter" class="org.baeldung.aop.PerformanceAspect"/>
|
||||
<bean id="fooDao" class="org.baeldung.dao.FooDao"/>
|
||||
<bean id="perfomanceMeter" class="com.baeldung.aop.PerformanceAspect"/>
|
||||
<bean id="fooDao" class="com.baeldung.dao.FooDao"/>
|
||||
|
||||
<aop:config>
|
||||
<aop:pointcut id="anyDaoMethod" expression="@target(org.springframework.stereotype.Repository)"/>
|
|
@ -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"%>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>File Upload Example</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<h3>Enter The File to Upload (Single file)</h3>
|
||||
|
||||
<form:form method="POST" action="/spring-mvc-java/uploadFile" enctype="multipart/form-data">
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td>Select a file to upload</td>
|
||||
<td><input type="file" name="file" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><input type="submit" value="Submit" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</form:form>
|
||||
|
||||
<br />
|
||||
|
||||
<h3>Enter The Files to Upload (Multiple files)</h3>
|
||||
|
||||
<form:form method="POST" action="/spring-mvc-java/uploadMultiFile" enctype="multipart/form-data">
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td>Select a file to upload</td>
|
||||
<td><input type="file" name="files" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Select a file to upload</td>
|
||||
<td><input type="file" name="files" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Select a file to upload</td>
|
||||
<td><input type="file" name="files" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><input type="submit" value="Submit" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</form:form>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
|
@ -0,0 +1,36 @@
|
|||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<title>Spring MVC File Upload</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h2>Submitted File (Single)</h2>
|
||||
<table>
|
||||
<tr>
|
||||
<td>OriginalFileName :</td>
|
||||
<td>${file.originalFilename}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Type :</td>
|
||||
<td>${file.contentType}</td>
|
||||
</tr>
|
||||
</table>
|
||||
<br />
|
||||
|
||||
<h2>Submitted Files (Multiple)</h2>
|
||||
<table>
|
||||
<c:forEach items="${files}" var="file">
|
||||
<tr>
|
||||
<td>OriginalFileName :</td>
|
||||
<td>${file.originalFilename}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Type :</td>
|
||||
<td>${file.contentType}</td>
|
||||
</tr>
|
||||
</c:forEach>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
|
@ -16,7 +16,7 @@
|
|||
</context-param>
|
||||
<context-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>org.baeldung.spring.web.config</param-value>
|
||||
<param-value>com.baeldung.spring.web.config</param-value>
|
||||
</context-param>
|
||||
|
||||
<listener>
|
||||
|
|
|
@ -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;
|
|
@ -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;
|
|
@ -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;
|
|
@ -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
|
|
@ -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 {
|
||||
}
|
|
@ -1,7 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
|
||||
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
|
||||
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.wst.jsdt.core.javascriptValidator"/>
|
||||
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
|
||||
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
|
||||
</launchConfiguration>
|
|
@ -1,12 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" path="src/main/webapp"/>
|
||||
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
|
||||
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
|
||||
<attributes>
|
||||
<attribute name="hide" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
|
||||
<classpathentry kind="output" path=""/>
|
||||
</classpath>
|
|
@ -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
|
|
@ -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
|
|
@ -1,4 +0,0 @@
|
|||
activeProfiles=
|
||||
eclipse.preferences.version=1
|
||||
resolveWorkspaceProjects=true
|
||||
version=1
|
|
@ -1,2 +0,0 @@
|
|||
eclipse.preferences.version=1
|
||||
org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false
|
|
@ -1,10 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
|
||||
<wb-module deploy-name="spring-mvc-xml">
|
||||
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
|
||||
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
|
||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
|
||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
|
||||
<property name="java-output-path" value="/spring-mvc-xml/target/classes"/>
|
||||
<property name="context-root" value="spring-mvc-xml"/>
|
||||
</wb-module>
|
||||
</project-modules>
|
|
@ -1,6 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<faceted-project>
|
||||
<installed facet="wst.jsdt.web" version="1.0"/>
|
||||
<installed facet="jst.web" version="3.0"/>
|
||||
<installed facet="java" version="1.8"/>
|
||||
</faceted-project>
|
|
@ -1 +0,0 @@
|
|||
org.eclipse.wst.jsdt.launching.baseBrowserLibrary
|
|
@ -1 +0,0 @@
|
|||
Window
|
|
@ -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
|
|
@ -1,2 +0,0 @@
|
|||
eclipse.preferences.version=1
|
||||
org.eclipse.wst.ws.service.policy.projectEnabled=false
|
|
@ -1,14 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beansProjectDescription>
|
||||
<version>1</version>
|
||||
<pluginVersion><![CDATA[3.2.0.201303060654-RELEASE]]></pluginVersion>
|
||||
<configSuffixes>
|
||||
<configSuffix><![CDATA[xml]]></configSuffix>
|
||||
</configSuffixes>
|
||||
<enableImports><![CDATA[false]]></enableImports>
|
||||
<configs>
|
||||
<config>src/main/webapp/WEB-INF/mvc-servlet.xml</config>
|
||||
</configs>
|
||||
<configSets>
|
||||
</configSets>
|
||||
</beansProjectDescription>
|
|
@ -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
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue