diff --git a/.travis.yml b/.travis.yml
index 4df8a96f6d..5e2d690b4e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -4,7 +4,7 @@ before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: skip
-script: travis_wait 60 mvn -q install
+script: travis_wait 60 mvn -q install -Pdefault
sudo: required
diff --git a/README.md b/README.md
index 1d916c8409..d018783465 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@ In additional to Spring, the following technologies are in focus: `core Java`, `
Building the project
====================
-To do the full build, do: `mvn install -Dgib.enabled=false`
+To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
Working with the code in Eclipse
diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml
new file mode 100644
index 0000000000..39da518269
--- /dev/null
+++ b/apache-avro/pom.xml
@@ -0,0 +1,88 @@
+
+
+ 4.0.0
+ com.baeldung
+ apache-avro-tutorial
+ 0.0.1-SNAPSHOT
+
+
+ UTF-8
+ 3.5
+ 1.8.2
+ 1.8
+ 1.7.25
+
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ junit
+ junit
+ 4.10
+ test
+
+
+ org.slf4j
+ slf4j-simple
+ ${slf4j.version}
+ compile
+
+
+ org.apache.avro
+ avro
+ ${avro.version}
+
+
+ org.apache.avro
+ avro-compiler
+ ${avro.version}
+
+
+
+ org.apache.avro
+ avro-maven-plugin
+ ${avro.version}
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${compiler-plugin.version}
+
+ ${java.version}
+ ${java.version}
+
+
+
+ org.apache.avro
+ avro-maven-plugin
+ ${avro.version}
+
+
+ schemas
+ generate-sources
+
+ schema
+ protocol
+ idl-protocol
+
+
+ ${project.basedir}/src/main/resources/
+ ${project.basedir}/src/main/java/
+
+
+
+
+
+
+
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/AvroClassGenerator.java b/apache-avro/src/main/java/com/baeldung/avro/util/AvroClassGenerator.java
new file mode 100644
index 0000000000..718b62a752
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/AvroClassGenerator.java
@@ -0,0 +1,14 @@
+package com.baeldung.avro.util;
+
+import org.apache.avro.Schema;
+import org.apache.avro.compiler.specific.SpecificCompiler;
+
+import java.io.File;
+import java.io.IOException;
+
+public class AvroClassGenerator {
+ public void generateAvroClasses() throws IOException {
+ SpecificCompiler compiler = new SpecificCompiler(new Schema.Parser().parse(new File("src/main/resources/avroHttpRequest-schema.avsc")));
+ compiler.compileToDestination(new File("src/main/resources"), new File("src/main/java"));
+ }
+}
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/AvroSchemaBuilder.java b/apache-avro/src/main/java/com/baeldung/avro/util/AvroSchemaBuilder.java
new file mode 100644
index 0000000000..4a1314cd00
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/AvroSchemaBuilder.java
@@ -0,0 +1,24 @@
+package com.baeldung.avro.util;
+
+
+import org.apache.avro.Schema;
+import org.apache.avro.SchemaBuilder;
+
+public class AvroSchemaBuilder {
+
+ public Schema createAvroHttpRequestSchema(){
+
+ Schema clientIdentifier = SchemaBuilder.record("ClientIdentifier").namespace("com.baeldung.avro.model")
+ .fields().requiredString("hostName").requiredString("ipAddress").endRecord();
+
+ Schema avroHttpRequest = SchemaBuilder.record("AvroHttpRequest").namespace("com.baeldung.avro.model").fields()
+ .requiredLong("requestTime")
+ .name("clientIdentifier").type(clientIdentifier).noDefault()
+ .name("employeeNames").type().array().items().stringType().arrayDefault(null)
+ .name("active").type().enumeration("Active").symbols("YES", "NO").noDefault()
+ .endRecord();
+ return avroHttpRequest;
+ }
+}
+
+
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/model/Active.java b/apache-avro/src/main/java/com/baeldung/avro/util/model/Active.java
new file mode 100644
index 0000000000..3ae0508394
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/model/Active.java
@@ -0,0 +1,13 @@
+/**
+ * Autogenerated by Avro
+ *
+ * DO NOT EDIT DIRECTLY
+ */
+package com.baeldung.avro.util.model;
+@SuppressWarnings("all")
+@org.apache.avro.specific.AvroGenerated
+public enum Active {
+ YES, NO ;
+ public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"enum\",\"name\":\"Active\",\"namespace\":\"com.baeldung.avro.model\",\"symbols\":[\"YES\",\"NO\"]}");
+ public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
+}
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/model/AvroHttpRequest.java b/apache-avro/src/main/java/com/baeldung/avro/util/model/AvroHttpRequest.java
new file mode 100644
index 0000000000..56b36050a5
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/model/AvroHttpRequest.java
@@ -0,0 +1,491 @@
+/**
+ * Autogenerated by Avro
+ *
+ * DO NOT EDIT DIRECTLY
+ */
+package com.baeldung.avro.util.model;
+
+import org.apache.avro.specific.SpecificData;
+import org.apache.avro.message.BinaryMessageEncoder;
+import org.apache.avro.message.BinaryMessageDecoder;
+import org.apache.avro.message.SchemaStore;
+
+@SuppressWarnings("all")
+@org.apache.avro.specific.AvroGenerated
+public class AvroHttpRequest extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
+ private static final long serialVersionUID = -8649010116827875312L;
+ public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"AvroHttpRequest\",\"namespace\":\"com.baeldung.avro.model\",\"fields\":[{\"name\":\"requestTime\",\"type\":\"long\"},{\"name\":\"clientIdentifier\",\"type\":{\"type\":\"record\",\"name\":\"ClientIdentifier\",\"fields\":[{\"name\":\"hostName\",\"type\":\"string\"},{\"name\":\"ipAddress\",\"type\":\"string\"}]}},{\"name\":\"employeeNames\",\"type\":{\"type\":\"array\",\"items\":\"string\"},\"default\":null},{\"name\":\"active\",\"type\":{\"type\":\"enum\",\"name\":\"Active\",\"symbols\":[\"YES\",\"NO\"]}}]}");
+ public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
+
+ private static SpecificData MODEL$ = new SpecificData();
+
+ private static final BinaryMessageEncoder ENCODER =
+ new BinaryMessageEncoder(MODEL$, SCHEMA$);
+
+ private static final BinaryMessageDecoder DECODER =
+ new BinaryMessageDecoder(MODEL$, SCHEMA$);
+
+ /**
+ * Return the BinaryMessageDecoder instance used by this class.
+ */
+ public static BinaryMessageDecoder getDecoder() {
+ return DECODER;
+ }
+
+ /**
+ * Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
+ * @param resolver a {@link SchemaStore} used to find schemas by fingerprint
+ */
+ public static BinaryMessageDecoder createDecoder(SchemaStore resolver) {
+ return new BinaryMessageDecoder(MODEL$, SCHEMA$, resolver);
+ }
+
+ /** Serializes this AvroHttpRequest to a ByteBuffer. */
+ public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
+ return ENCODER.encode(this);
+ }
+
+ /** Deserializes a AvroHttpRequest from a ByteBuffer. */
+ public static AvroHttpRequest fromByteBuffer(
+ java.nio.ByteBuffer b) throws java.io.IOException {
+ return DECODER.decode(b);
+ }
+
+ @Deprecated public long requestTime;
+ @Deprecated public ClientIdentifier clientIdentifier;
+ @Deprecated public java.util.List employeeNames;
+ @Deprecated public Active active;
+
+ /**
+ * Default constructor. Note that this does not initialize fields
+ * to their default values from the schema. If that is desired then
+ * one should use newBuilder().
+ */
+ public AvroHttpRequest() {}
+
+ /**
+ * All-args constructor.
+ * @param requestTime The new value for requestTime
+ * @param clientIdentifier The new value for clientIdentifier
+ * @param employeeNames The new value for employeeNames
+ * @param active The new value for active
+ */
+ public AvroHttpRequest(java.lang.Long requestTime, ClientIdentifier clientIdentifier, java.util.List employeeNames, Active active) {
+ this.requestTime = requestTime;
+ this.clientIdentifier = clientIdentifier;
+ this.employeeNames = employeeNames;
+ this.active = active;
+ }
+
+ public org.apache.avro.Schema getSchema() { return SCHEMA$; }
+ // Used by DatumWriter. Applications should not call.
+ public java.lang.Object get(int field$) {
+ switch (field$) {
+ case 0: return requestTime;
+ case 1: return clientIdentifier;
+ case 2: return employeeNames;
+ case 3: return active;
+ default: throw new org.apache.avro.AvroRuntimeException("Bad index");
+ }
+ }
+
+ // Used by DatumReader. Applications should not call.
+ @SuppressWarnings(value="unchecked")
+ public void put(int field$, java.lang.Object value$) {
+ switch (field$) {
+ case 0: requestTime = (java.lang.Long)value$; break;
+ case 1: clientIdentifier = (ClientIdentifier)value$; break;
+ case 2: employeeNames = (java.util.List)value$; break;
+ case 3: active = (Active)value$; break;
+ default: throw new org.apache.avro.AvroRuntimeException("Bad index");
+ }
+ }
+
+ /**
+ * Gets the value of the 'requestTime' field.
+ * @return The value of the 'requestTime' field.
+ */
+ public java.lang.Long getRequestTime() {
+ return requestTime;
+ }
+
+ /**
+ * Sets the value of the 'requestTime' field.
+ * @param value the value to set.
+ */
+ public void setRequestTime(java.lang.Long value) {
+ this.requestTime = value;
+ }
+
+ /**
+ * Gets the value of the 'clientIdentifier' field.
+ * @return The value of the 'clientIdentifier' field.
+ */
+ public ClientIdentifier getClientIdentifier() {
+ return clientIdentifier;
+ }
+
+ /**
+ * Sets the value of the 'clientIdentifier' field.
+ * @param value the value to set.
+ */
+ public void setClientIdentifier(ClientIdentifier value) {
+ this.clientIdentifier = value;
+ }
+
+ /**
+ * Gets the value of the 'employeeNames' field.
+ * @return The value of the 'employeeNames' field.
+ */
+ public java.util.List getEmployeeNames() {
+ return employeeNames;
+ }
+
+ /**
+ * Sets the value of the 'employeeNames' field.
+ * @param value the value to set.
+ */
+ public void setEmployeeNames(java.util.List value) {
+ this.employeeNames = value;
+ }
+
+ /**
+ * Gets the value of the 'active' field.
+ * @return The value of the 'active' field.
+ */
+ public Active getActive() {
+ return active;
+ }
+
+ /**
+ * Sets the value of the 'active' field.
+ * @param value the value to set.
+ */
+ public void setActive(Active value) {
+ this.active = value;
+ }
+
+ /**
+ * Creates a new AvroHttpRequest RecordBuilder.
+ * @return A new AvroHttpRequest RecordBuilder
+ */
+ public static AvroHttpRequest.Builder newBuilder() {
+ return new AvroHttpRequest.Builder();
+ }
+
+ /**
+ * Creates a new AvroHttpRequest RecordBuilder by copying an existing Builder.
+ * @param other The existing builder to copy.
+ * @return A new AvroHttpRequest RecordBuilder
+ */
+ public static AvroHttpRequest.Builder newBuilder(AvroHttpRequest.Builder other) {
+ return new AvroHttpRequest.Builder(other);
+ }
+
+ /**
+ * Creates a new AvroHttpRequest RecordBuilder by copying an existing AvroHttpRequest instance.
+ * @param other The existing instance to copy.
+ * @return A new AvroHttpRequest RecordBuilder
+ */
+ public static AvroHttpRequest.Builder newBuilder(AvroHttpRequest other) {
+ return new AvroHttpRequest.Builder(other);
+ }
+
+ /**
+ * RecordBuilder for AvroHttpRequest instances.
+ */
+ public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase
+ implements org.apache.avro.data.RecordBuilder {
+
+ private long requestTime;
+ private ClientIdentifier clientIdentifier;
+ private ClientIdentifier.Builder clientIdentifierBuilder;
+ private java.util.List employeeNames;
+ private Active active;
+
+ /** Creates a new Builder */
+ private Builder() {
+ super(SCHEMA$);
+ }
+
+ /**
+ * Creates a Builder by copying an existing Builder.
+ * @param other The existing Builder to copy.
+ */
+ private Builder(AvroHttpRequest.Builder other) {
+ super(other);
+ if (isValidValue(fields()[0], other.requestTime)) {
+ this.requestTime = data().deepCopy(fields()[0].schema(), other.requestTime);
+ fieldSetFlags()[0] = true;
+ }
+ if (isValidValue(fields()[1], other.clientIdentifier)) {
+ this.clientIdentifier = data().deepCopy(fields()[1].schema(), other.clientIdentifier);
+ fieldSetFlags()[1] = true;
+ }
+ if (other.hasClientIdentifierBuilder()) {
+ this.clientIdentifierBuilder = ClientIdentifier.newBuilder(other.getClientIdentifierBuilder());
+ }
+ if (isValidValue(fields()[2], other.employeeNames)) {
+ this.employeeNames = data().deepCopy(fields()[2].schema(), other.employeeNames);
+ fieldSetFlags()[2] = true;
+ }
+ if (isValidValue(fields()[3], other.active)) {
+ this.active = data().deepCopy(fields()[3].schema(), other.active);
+ fieldSetFlags()[3] = true;
+ }
+ }
+
+ /**
+ * Creates a Builder by copying an existing AvroHttpRequest instance
+ * @param other The existing instance to copy.
+ */
+ private Builder(AvroHttpRequest other) {
+ super(SCHEMA$);
+ if (isValidValue(fields()[0], other.requestTime)) {
+ this.requestTime = data().deepCopy(fields()[0].schema(), other.requestTime);
+ fieldSetFlags()[0] = true;
+ }
+ if (isValidValue(fields()[1], other.clientIdentifier)) {
+ this.clientIdentifier = data().deepCopy(fields()[1].schema(), other.clientIdentifier);
+ fieldSetFlags()[1] = true;
+ }
+ this.clientIdentifierBuilder = null;
+ if (isValidValue(fields()[2], other.employeeNames)) {
+ this.employeeNames = data().deepCopy(fields()[2].schema(), other.employeeNames);
+ fieldSetFlags()[2] = true;
+ }
+ if (isValidValue(fields()[3], other.active)) {
+ this.active = data().deepCopy(fields()[3].schema(), other.active);
+ fieldSetFlags()[3] = true;
+ }
+ }
+
+ /**
+ * Gets the value of the 'requestTime' field.
+ * @return The value.
+ */
+ public java.lang.Long getRequestTime() {
+ return requestTime;
+ }
+
+ /**
+ * Sets the value of the 'requestTime' field.
+ * @param value The value of 'requestTime'.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder setRequestTime(long value) {
+ validate(fields()[0], value);
+ this.requestTime = value;
+ fieldSetFlags()[0] = true;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'requestTime' field has been set.
+ * @return True if the 'requestTime' field has been set, false otherwise.
+ */
+ public boolean hasRequestTime() {
+ return fieldSetFlags()[0];
+ }
+
+
+ /**
+ * Clears the value of the 'requestTime' field.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder clearRequestTime() {
+ fieldSetFlags()[0] = false;
+ return this;
+ }
+
+ /**
+ * Gets the value of the 'clientIdentifier' field.
+ * @return The value.
+ */
+ public ClientIdentifier getClientIdentifier() {
+ return clientIdentifier;
+ }
+
+ /**
+ * Sets the value of the 'clientIdentifier' field.
+ * @param value The value of 'clientIdentifier'.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder setClientIdentifier(ClientIdentifier value) {
+ validate(fields()[1], value);
+ this.clientIdentifierBuilder = null;
+ this.clientIdentifier = value;
+ fieldSetFlags()[1] = true;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'clientIdentifier' field has been set.
+ * @return True if the 'clientIdentifier' field has been set, false otherwise.
+ */
+ public boolean hasClientIdentifier() {
+ return fieldSetFlags()[1];
+ }
+
+ /**
+ * Gets the Builder instance for the 'clientIdentifier' field and creates one if it doesn't exist yet.
+ * @return This builder.
+ */
+ public ClientIdentifier.Builder getClientIdentifierBuilder() {
+ if (clientIdentifierBuilder == null) {
+ if (hasClientIdentifier()) {
+ setClientIdentifierBuilder(ClientIdentifier.newBuilder(clientIdentifier));
+ } else {
+ setClientIdentifierBuilder(ClientIdentifier.newBuilder());
+ }
+ }
+ return clientIdentifierBuilder;
+ }
+
+ /**
+ * Sets the Builder instance for the 'clientIdentifier' field
+ * @param value The builder instance that must be set.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder setClientIdentifierBuilder(ClientIdentifier.Builder value) {
+ clearClientIdentifier();
+ clientIdentifierBuilder = value;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'clientIdentifier' field has an active Builder instance
+ * @return True if the 'clientIdentifier' field has an active Builder instance
+ */
+ public boolean hasClientIdentifierBuilder() {
+ return clientIdentifierBuilder != null;
+ }
+
+ /**
+ * Clears the value of the 'clientIdentifier' field.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder clearClientIdentifier() {
+ clientIdentifier = null;
+ clientIdentifierBuilder = null;
+ fieldSetFlags()[1] = false;
+ return this;
+ }
+
+ /**
+ * Gets the value of the 'employeeNames' field.
+ * @return The value.
+ */
+ public java.util.List getEmployeeNames() {
+ return employeeNames;
+ }
+
+ /**
+ * Sets the value of the 'employeeNames' field.
+ * @param value The value of 'employeeNames'.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder setEmployeeNames(java.util.List value) {
+ validate(fields()[2], value);
+ this.employeeNames = value;
+ fieldSetFlags()[2] = true;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'employeeNames' field has been set.
+ * @return True if the 'employeeNames' field has been set, false otherwise.
+ */
+ public boolean hasEmployeeNames() {
+ return fieldSetFlags()[2];
+ }
+
+
+ /**
+ * Clears the value of the 'employeeNames' field.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder clearEmployeeNames() {
+ employeeNames = null;
+ fieldSetFlags()[2] = false;
+ return this;
+ }
+
+ /**
+ * Gets the value of the 'active' field.
+ * @return The value.
+ */
+ public Active getActive() {
+ return active;
+ }
+
+ /**
+ * Sets the value of the 'active' field.
+ * @param value The value of 'active'.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder setActive(Active value) {
+ validate(fields()[3], value);
+ this.active = value;
+ fieldSetFlags()[3] = true;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'active' field has been set.
+ * @return True if the 'active' field has been set, false otherwise.
+ */
+ public boolean hasActive() {
+ return fieldSetFlags()[3];
+ }
+
+
+ /**
+ * Clears the value of the 'active' field.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder clearActive() {
+ active = null;
+ fieldSetFlags()[3] = false;
+ return this;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public AvroHttpRequest build() {
+ try {
+ AvroHttpRequest record = new AvroHttpRequest();
+ record.requestTime = fieldSetFlags()[0] ? this.requestTime : (java.lang.Long) defaultValue(fields()[0]);
+ if (clientIdentifierBuilder != null) {
+ record.clientIdentifier = this.clientIdentifierBuilder.build();
+ } else {
+ record.clientIdentifier = fieldSetFlags()[1] ? this.clientIdentifier : (ClientIdentifier) defaultValue(fields()[1]);
+ }
+ record.employeeNames = fieldSetFlags()[2] ? this.employeeNames : (java.util.List) defaultValue(fields()[2]);
+ record.active = fieldSetFlags()[3] ? this.active : (Active) defaultValue(fields()[3]);
+ return record;
+ } catch (java.lang.Exception e) {
+ throw new org.apache.avro.AvroRuntimeException(e);
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static final org.apache.avro.io.DatumWriter
+ WRITER$ = (org.apache.avro.io.DatumWriter)MODEL$.createDatumWriter(SCHEMA$);
+
+ @Override public void writeExternal(java.io.ObjectOutput out)
+ throws java.io.IOException {
+ WRITER$.write(this, SpecificData.getEncoder(out));
+ }
+
+ @SuppressWarnings("unchecked")
+ private static final org.apache.avro.io.DatumReader
+ READER$ = (org.apache.avro.io.DatumReader)MODEL$.createDatumReader(SCHEMA$);
+
+ @Override public void readExternal(java.io.ObjectInput in)
+ throws java.io.IOException {
+ READER$.read(this, SpecificData.getDecoder(in));
+ }
+
+}
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/model/ClientIdentifier.java b/apache-avro/src/main/java/com/baeldung/avro/util/model/ClientIdentifier.java
new file mode 100644
index 0000000000..503dde40df
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/model/ClientIdentifier.java
@@ -0,0 +1,308 @@
+/**
+ * Autogenerated by Avro
+ *
+ * DO NOT EDIT DIRECTLY
+ */
+package com.baeldung.avro.util.model;
+
+import org.apache.avro.specific.SpecificData;
+import org.apache.avro.message.BinaryMessageEncoder;
+import org.apache.avro.message.BinaryMessageDecoder;
+import org.apache.avro.message.SchemaStore;
+
+@SuppressWarnings("all")
+@org.apache.avro.specific.AvroGenerated
+public class ClientIdentifier extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
+ private static final long serialVersionUID = 8754570983127295424L;
+ public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"ClientIdentifier\",\"namespace\":\"com.baeldung.avro.model\",\"fields\":[{\"name\":\"hostName\",\"type\":\"string\"},{\"name\":\"ipAddress\",\"type\":\"string\"}]}");
+ public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
+
+ private static SpecificData MODEL$ = new SpecificData();
+
+ private static final BinaryMessageEncoder ENCODER =
+ new BinaryMessageEncoder(MODEL$, SCHEMA$);
+
+ private static final BinaryMessageDecoder DECODER =
+ new BinaryMessageDecoder(MODEL$, SCHEMA$);
+
+ /**
+ * Return the BinaryMessageDecoder instance used by this class.
+ */
+ public static BinaryMessageDecoder getDecoder() {
+ return DECODER;
+ }
+
+ /**
+ * Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
+ * @param resolver a {@link SchemaStore} used to find schemas by fingerprint
+ */
+ public static BinaryMessageDecoder createDecoder(SchemaStore resolver) {
+ return new BinaryMessageDecoder(MODEL$, SCHEMA$, resolver);
+ }
+
+ /** Serializes this ClientIdentifier to a ByteBuffer. */
+ public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
+ return ENCODER.encode(this);
+ }
+
+ /** Deserializes a ClientIdentifier from a ByteBuffer. */
+ public static ClientIdentifier fromByteBuffer(
+ java.nio.ByteBuffer b) throws java.io.IOException {
+ return DECODER.decode(b);
+ }
+
+ @Deprecated public java.lang.CharSequence hostName;
+ @Deprecated public java.lang.CharSequence ipAddress;
+
+ /**
+ * Default constructor. Note that this does not initialize fields
+ * to their default values from the schema. If that is desired then
+ * one should use newBuilder().
+ */
+ public ClientIdentifier() {}
+
+ /**
+ * All-args constructor.
+ * @param hostName The new value for hostName
+ * @param ipAddress The new value for ipAddress
+ */
+ public ClientIdentifier(java.lang.CharSequence hostName, java.lang.CharSequence ipAddress) {
+ this.hostName = hostName;
+ this.ipAddress = ipAddress;
+ }
+
+ public org.apache.avro.Schema getSchema() { return SCHEMA$; }
+ // Used by DatumWriter. Applications should not call.
+ public java.lang.Object get(int field$) {
+ switch (field$) {
+ case 0: return hostName;
+ case 1: return ipAddress;
+ default: throw new org.apache.avro.AvroRuntimeException("Bad index");
+ }
+ }
+
+ // Used by DatumReader. Applications should not call.
+ @SuppressWarnings(value="unchecked")
+ public void put(int field$, java.lang.Object value$) {
+ switch (field$) {
+ case 0: hostName = (java.lang.CharSequence)value$; break;
+ case 1: ipAddress = (java.lang.CharSequence)value$; break;
+ default: throw new org.apache.avro.AvroRuntimeException("Bad index");
+ }
+ }
+
+ /**
+ * Gets the value of the 'hostName' field.
+ * @return The value of the 'hostName' field.
+ */
+ public java.lang.CharSequence getHostName() {
+ return hostName;
+ }
+
+ /**
+ * Sets the value of the 'hostName' field.
+ * @param value the value to set.
+ */
+ public void setHostName(java.lang.CharSequence value) {
+ this.hostName = value;
+ }
+
+ /**
+ * Gets the value of the 'ipAddress' field.
+ * @return The value of the 'ipAddress' field.
+ */
+ public java.lang.CharSequence getIpAddress() {
+ return ipAddress;
+ }
+
+ /**
+ * Sets the value of the 'ipAddress' field.
+ * @param value the value to set.
+ */
+ public void setIpAddress(java.lang.CharSequence value) {
+ this.ipAddress = value;
+ }
+
+ /**
+ * Creates a new ClientIdentifier RecordBuilder.
+ * @return A new ClientIdentifier RecordBuilder
+ */
+ public static ClientIdentifier.Builder newBuilder() {
+ return new ClientIdentifier.Builder();
+ }
+
+ /**
+ * Creates a new ClientIdentifier RecordBuilder by copying an existing Builder.
+ * @param other The existing builder to copy.
+ * @return A new ClientIdentifier RecordBuilder
+ */
+ public static ClientIdentifier.Builder newBuilder(ClientIdentifier.Builder other) {
+ return new ClientIdentifier.Builder(other);
+ }
+
+ /**
+ * Creates a new ClientIdentifier RecordBuilder by copying an existing ClientIdentifier instance.
+ * @param other The existing instance to copy.
+ * @return A new ClientIdentifier RecordBuilder
+ */
+ public static ClientIdentifier.Builder newBuilder(ClientIdentifier other) {
+ return new ClientIdentifier.Builder(other);
+ }
+
+ /**
+ * RecordBuilder for ClientIdentifier instances.
+ */
+ public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase
+ implements org.apache.avro.data.RecordBuilder {
+
+ private java.lang.CharSequence hostName;
+ private java.lang.CharSequence ipAddress;
+
+ /** Creates a new Builder */
+ private Builder() {
+ super(SCHEMA$);
+ }
+
+ /**
+ * Creates a Builder by copying an existing Builder.
+ * @param other The existing Builder to copy.
+ */
+ private Builder(ClientIdentifier.Builder other) {
+ super(other);
+ if (isValidValue(fields()[0], other.hostName)) {
+ this.hostName = data().deepCopy(fields()[0].schema(), other.hostName);
+ fieldSetFlags()[0] = true;
+ }
+ if (isValidValue(fields()[1], other.ipAddress)) {
+ this.ipAddress = data().deepCopy(fields()[1].schema(), other.ipAddress);
+ fieldSetFlags()[1] = true;
+ }
+ }
+
+ /**
+ * Creates a Builder by copying an existing ClientIdentifier instance
+ * @param other The existing instance to copy.
+ */
+ private Builder(ClientIdentifier other) {
+ super(SCHEMA$);
+ if (isValidValue(fields()[0], other.hostName)) {
+ this.hostName = data().deepCopy(fields()[0].schema(), other.hostName);
+ fieldSetFlags()[0] = true;
+ }
+ if (isValidValue(fields()[1], other.ipAddress)) {
+ this.ipAddress = data().deepCopy(fields()[1].schema(), other.ipAddress);
+ fieldSetFlags()[1] = true;
+ }
+ }
+
+ /**
+ * Gets the value of the 'hostName' field.
+ * @return The value.
+ */
+ public java.lang.CharSequence getHostName() {
+ return hostName;
+ }
+
+ /**
+ * Sets the value of the 'hostName' field.
+ * @param value The value of 'hostName'.
+ * @return This builder.
+ */
+ public ClientIdentifier.Builder setHostName(java.lang.CharSequence value) {
+ validate(fields()[0], value);
+ this.hostName = value;
+ fieldSetFlags()[0] = true;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'hostName' field has been set.
+ * @return True if the 'hostName' field has been set, false otherwise.
+ */
+ public boolean hasHostName() {
+ return fieldSetFlags()[0];
+ }
+
+
+ /**
+ * Clears the value of the 'hostName' field.
+ * @return This builder.
+ */
+ public ClientIdentifier.Builder clearHostName() {
+ hostName = null;
+ fieldSetFlags()[0] = false;
+ return this;
+ }
+
+ /**
+ * Gets the value of the 'ipAddress' field.
+ * @return The value.
+ */
+ public java.lang.CharSequence getIpAddress() {
+ return ipAddress;
+ }
+
+ /**
+ * Sets the value of the 'ipAddress' field.
+ * @param value The value of 'ipAddress'.
+ * @return This builder.
+ */
+ public ClientIdentifier.Builder setIpAddress(java.lang.CharSequence value) {
+ validate(fields()[1], value);
+ this.ipAddress = value;
+ fieldSetFlags()[1] = true;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'ipAddress' field has been set.
+ * @return True if the 'ipAddress' field has been set, false otherwise.
+ */
+ public boolean hasIpAddress() {
+ return fieldSetFlags()[1];
+ }
+
+
+ /**
+ * Clears the value of the 'ipAddress' field.
+ * @return This builder.
+ */
+ public ClientIdentifier.Builder clearIpAddress() {
+ ipAddress = null;
+ fieldSetFlags()[1] = false;
+ return this;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public ClientIdentifier build() {
+ try {
+ ClientIdentifier record = new ClientIdentifier();
+ record.hostName = fieldSetFlags()[0] ? this.hostName : (java.lang.CharSequence) defaultValue(fields()[0]);
+ record.ipAddress = fieldSetFlags()[1] ? this.ipAddress : (java.lang.CharSequence) defaultValue(fields()[1]);
+ return record;
+ } catch (java.lang.Exception e) {
+ throw new org.apache.avro.AvroRuntimeException(e);
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static final org.apache.avro.io.DatumWriter
+ WRITER$ = (org.apache.avro.io.DatumWriter)MODEL$.createDatumWriter(SCHEMA$);
+
+ @Override public void writeExternal(java.io.ObjectOutput out)
+ throws java.io.IOException {
+ WRITER$.write(this, SpecificData.getEncoder(out));
+ }
+
+ @SuppressWarnings("unchecked")
+ private static final org.apache.avro.io.DatumReader
+ READER$ = (org.apache.avro.io.DatumReader)MODEL$.createDatumReader(SCHEMA$);
+
+ @Override public void readExternal(java.io.ObjectInput in)
+ throws java.io.IOException {
+ READER$.read(this, SpecificData.getDecoder(in));
+ }
+
+}
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
new file mode 100644
index 0000000000..d2219a45f2
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
@@ -0,0 +1,33 @@
+package com.baeldung.avro.util.serealization;
+
+import com.baeldung.avro.util.model.AvroHttpRequest;
+import org.apache.avro.io.DatumReader;
+import org.apache.avro.io.Decoder;
+import org.apache.avro.io.DecoderFactory;
+import org.apache.avro.specific.SpecificDatumReader;
+
+import java.io.IOException;
+
+public class AvroDeSerealizer {
+
+public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data){
+ DatumReader reader = new SpecificDatumReader<>(AvroHttpRequest.class);
+ Decoder decoder = null;
+ try {
+ decoder = DecoderFactory.get().jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
+ return reader.read(null, decoder);
+ } catch (IOException e) {
+ return null;
+ }
+}
+
+public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data){
+ DatumReader employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
+ Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);
+ try {
+ return employeeReader.read(null, decoder);
+ } catch (IOException e) {
+ return null;
+ }
+}
+}
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
new file mode 100644
index 0000000000..f56c89e201
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
@@ -0,0 +1,44 @@
+package com.baeldung.avro.util.serealization;
+
+import com.baeldung.avro.util.model.AvroHttpRequest;
+import org.apache.avro.io.*;
+import org.apache.avro.specific.SpecificDatumWriter;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+public class AvroSerealizer {
+
+public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request){
+ DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
+ byte[] data = new byte[0];
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ Encoder jsonEncoder = null;
+ try {
+ jsonEncoder = EncoderFactory.get().jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
+ writer.write(request, jsonEncoder);
+ jsonEncoder.flush();
+ data = stream.toByteArray();
+ } catch (IOException e) {
+ data =null;
+ }
+ return data;
+}
+
+public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request){
+ DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
+ byte[] data = new byte[0];
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ Encoder jsonEncoder = EncoderFactory.get().binaryEncoder(stream,null);
+ try {
+ writer.write(request, jsonEncoder);
+ jsonEncoder.flush();
+ data = stream.toByteArray();
+ } catch (IOException e) {
+ data = null;
+ }
+
+ return data;
+}
+
+}
diff --git a/apache-avro/src/main/resources/avroHttpRequest-schema.avsc b/apache-avro/src/main/resources/avroHttpRequest-schema.avsc
new file mode 100644
index 0000000000..18179a9cde
--- /dev/null
+++ b/apache-avro/src/main/resources/avroHttpRequest-schema.avsc
@@ -0,0 +1,47 @@
+{
+ "type":"record",
+ "name":"AvroHttpRequest",
+ "namespace":"com.baeldung.avro.model",
+ "fields":[
+ {
+ "name":"requestTime",
+ "type":"long"
+ },
+ {
+ "name":"clientIdentifier",
+ "type":{
+ "type":"record",
+ "name":"ClientIdentifier",
+ "fields":[
+ {
+ "name":"hostName",
+ "type":"string"
+ },
+ {
+ "name":"ipAddress",
+ "type":"string"
+ }
+ ]
+ }
+ },
+ {
+ "name":"employeeNames",
+ "type":{
+ "type":"array",
+ "items":"string"
+ },
+ "default":null
+ },
+ {
+ "name":"active",
+ "type":{
+ "type":"enum",
+ "name":"Active",
+ "symbols":[
+ "YES",
+ "NO"
+ ]
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java
new file mode 100644
index 0000000000..937a4ae650
--- /dev/null
+++ b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java
@@ -0,0 +1,75 @@
+package com.baeldung.avro.util.serealization;
+
+import com.baeldung.avro.util.model.Active;
+import com.baeldung.avro.util.model.AvroHttpRequest;
+import com.baeldung.avro.util.model.ClientIdentifier;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+import static org.junit.Assert.*;
+
+public class AvroSerealizerDeSerealizerTest {
+
+ AvroSerealizer serealizer;
+ AvroDeSerealizer deSerealizer;
+ AvroHttpRequest request;
+
+ @Before
+ public void setUp() throws Exception {
+ serealizer = new AvroSerealizer();
+ deSerealizer = new AvroDeSerealizer();
+
+ ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder().
+ setHostName("localhost").setIpAddress("255.255.255.0").build();
+
+ List employees = new ArrayList();
+ employees.add("James");
+ employees.add("Alice");
+ employees.add("David");
+ employees.add("Han");
+
+ request = AvroHttpRequest.newBuilder().setRequestTime(01l)
+ .setActive(Active.YES).setClientIdentifier(clientIdentifier)
+ .setEmployeeNames(employees).build();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ }
+
+@Test
+public void WhenSerialized_UsingJSONEncoder_ObjectGetsSerialized(){
+ byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
+ assertTrue(Objects.nonNull(data));
+ assertTrue(data.length > 0);
+}
+
+@Test
+public void WhenSerialized_UsingBinaryEncoder_ObjectGetsSerialized(){
+ byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
+ assertTrue(Objects.nonNull(data));
+ assertTrue(data.length > 0);
+}
+
+@Test
+public void WhenDeserialize_UsingJSONDecoder_ActualAndExpectedObjectsAreEqual(){
+ byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
+ AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
+ assertEquals(actualRequest,request);
+ assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
+}
+
+@Test
+public void WhenDeserialize_UsingBinaryecoder_ActualAndExpectedObjectsAreEqual(){
+ byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
+ AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
+ assertEquals(actualRequest,request);
+ assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
+}
+}
+
diff --git a/bootique/pom.xml b/bootique/pom.xml
index 6b2a0e2b99..880b9a516f 100644
--- a/bootique/pom.xml
+++ b/bootique/pom.xml
@@ -52,16 +52,21 @@
+
org.apache.maven.plugins
maven-shade-plugin
+ ${maven-shade-plugin.version}
+
com.baeldung.bootique.App
0.23
+
+ 2.4.3
\ No newline at end of file
diff --git a/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java b/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java
new file mode 100644
index 0000000000..f529e219a6
--- /dev/null
+++ b/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java
@@ -0,0 +1,14 @@
+package com.baeldung.java10.list;
+
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class CopyListServiceUnitTest {
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void whenModifyCopyOfList_thenThrowsException() {
+ List copyList = List.copyOf(Arrays.asList(1, 2, 3, 4));
+ }
+}
diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml
index 4b52237372..dee0634951 100644
--- a/core-java-8/pom.xml
+++ b/core-java-8/pom.xml
@@ -128,77 +128,6 @@
-
- org.apache.maven.plugins
- maven-jar-plugin
-
-
-
- true
- libs/
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
- org.apache.maven.plugins
- maven-assembly-plugin
-
-
- package
-
- single
-
-
- ${project.basedir}
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
- jar-with-dependencies
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-shade-plugin
-
-
-
- shade
-
-
- true
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
-
-
- com.jolira
- onejar-maven-plugin
-
-
-
- org.baeldung.executable.ExecutableMavenJar
- true
- ${project.build.finalName}-onejar.${project.packaging}
-
-
- one-jar
-
-
-
-
org.apache.maven.plugins
maven-compiler-plugin
diff --git a/core-java-8/src/main/java/com/baeldung/convertlisttomap/Animal.java b/core-java-8/src/main/java/com/baeldung/convertlisttomap/Animal.java
new file mode 100644
index 0000000000..b8eddf71a5
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/convertlisttomap/Animal.java
@@ -0,0 +1,27 @@
+package com.baeldung.convertlisttomap;
+
+public class Animal {
+ private int id;
+ private String name;
+
+ public Animal(int id, String name) {
+ this.id = id;
+ this.setName(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;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java b/core-java-8/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java
new file mode 100644
index 0000000000..679e753c56
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java
@@ -0,0 +1,52 @@
+package com.baeldung.convertlisttomap;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.apache.commons.collections4.IterableUtils;
+import org.apache.commons.collections4.MapUtils;
+import com.google.common.collect.Maps;
+
+public class ConvertListToMapService {
+
+ public Map convertListBeforeJava8(List list) {
+ Map map = new HashMap();
+ for (Animal animal : list) {
+ map.put(animal.getId(), animal);
+ }
+ return map;
+ }
+
+ public Map convertListAfterJava8(List list) {
+ Map map = list.stream().collect(Collectors.toMap(Animal::getId, animal -> animal));
+ return map;
+ }
+
+ public Map convertListWithGuava(List list) {
+
+ Map map = Maps.uniqueIndex(list, Animal::getId);
+ return map;
+ }
+
+ public Map convertListWithApacheCommons1(List list) {
+
+ Map map = new HashMap();
+
+ IterableUtils.forEach(list, animal -> {
+ map.put(animal.getId(), animal);
+ });
+
+ return map;
+ }
+
+ public Map convertListWithApacheCommons2(List list) {
+
+ Map map = new HashMap();
+
+ MapUtils.populateMap(map, list, Animal::getId);
+
+ return map;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/list/CopyListService.java b/core-java-8/src/main/java/com/baeldung/list/CopyListService.java
new file mode 100644
index 0000000000..55d5bb9379
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/list/CopyListService.java
@@ -0,0 +1,73 @@
+package com.baeldung.list;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class CopyListService {
+
+ public List copyListByConstructor(List source) {
+ return new ArrayList(source);
+ }
+
+ public List copyListByConstructorAndEditOneFlowerInTheNewList(List source) {
+ List flowers = new ArrayList<>(source);
+ if(flowers.size() > 0) {
+ flowers.get(0).setPetals(flowers.get(0).getPetals() * 3);
+ }
+
+ return flowers;
+ }
+
+ public List copyListByAddAllMethod(List source) {
+ List flowers = new ArrayList<>();
+ flowers.addAll(source);
+ return flowers;
+ }
+
+ public List copyListByAddAllMethodAndEditOneFlowerInTheNewList(List source) {
+ List flowers = new ArrayList<>();
+ flowers.addAll(source);
+
+ if(flowers.size() > 0) {
+ flowers.get(0).setPetals(flowers.get(0).getPetals() * 3);
+ }
+
+ return flowers;
+ }
+
+ public List copyListByCopyMethod(List source, List dest) {
+ Collections.copy(dest, source);
+ return dest;
+ }
+
+ public List copyListByStream(List source) {
+ return source.stream().collect(Collectors.toList());
+ }
+
+ public List copyListByStreamAndSkipFirstElement(List source) {
+ return source.stream().skip(1).collect(Collectors.toList());
+ }
+
+ public List copyListByStreamWithFilter(List source, Integer moreThanPetals) {
+ return source.stream().filter(f -> f.getPetals() > moreThanPetals).collect(Collectors.toList());
+ }
+
+ public List copyListByStreamWithOptional(List source) {
+ return Optional.ofNullable(source)
+ .map(List::stream)
+ .orElseGet(Stream::empty)
+ .collect(Collectors.toList());
+ }
+
+ public List copyListByStreamWithOptionalAndSkip(List source) {
+ return Optional.ofNullable(source)
+ .map(List::stream)
+ .orElseGet(Stream::empty)
+ .skip(1)
+ .collect(Collectors.toList());
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/list/Flower.java b/core-java-8/src/main/java/com/baeldung/list/Flower.java
new file mode 100644
index 0000000000..29c6a78326
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/list/Flower.java
@@ -0,0 +1,28 @@
+package com.baeldung.list;
+
+public class Flower {
+
+ private String name;
+ private int petals;
+
+ public Flower(String name, int petals) {
+ this.name = name;
+ this.petals = petals;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int getPetals() {
+ return petals;
+ }
+
+ public void setPetals(int petals) {
+ this.petals = petals;
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java b/core-java-8/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java
new file mode 100644
index 0000000000..4e78af08cd
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java
@@ -0,0 +1,73 @@
+package com.baeldung.convertlisttomap;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class ConvertListToMapServiceUnitTest {
+ List list;
+
+ private ConvertListToMapService convertListService;
+
+ @Before
+ public void init() {
+ this.convertListService = new ConvertListToMapService();
+ this.list = new ArrayList<>();
+
+ Animal cat = new Animal(1, "Cat");
+ list.add(cat);
+ Animal dog = new Animal(2, "Dog");
+ list.add(dog);
+ Animal pig = new Animal(3, "Pig");
+ list.add(pig);
+ Animal cow = new Animal(4, "Cow");
+ list.add(cow);
+ Animal goat = new Animal(5, "Goat");
+ list.add(goat);
+ }
+
+ @Test
+ public void givenAList_whenConvertBeforeJava8_thenReturnMapWithTheSameElements() {
+
+ Map map = convertListService.convertListBeforeJava8(list);
+
+ assertThat(map.values(), containsInAnyOrder(list.toArray()));
+ }
+
+ @Test
+ public void givenAList_whenConvertAfterJava8_thenReturnMapWithTheSameElements() {
+
+ Map map = convertListService.convertListAfterJava8(list);
+
+ assertThat(map.values(), containsInAnyOrder(list.toArray()));
+ }
+
+ @Test
+ public void givenAList_whenConvertWithGuava_thenReturnMapWithTheSameElements() {
+
+ Map map = convertListService.convertListWithGuava(list);
+
+ assertThat(map.values(), containsInAnyOrder(list.toArray()));
+ }
+
+ @Test
+ public void givenAList_whenConvertWithApacheCommons1_thenReturnMapWithTheSameElements() {
+
+ Map map = convertListService.convertListWithApacheCommons1(list);
+
+ assertThat(map.values(), containsInAnyOrder(list.toArray()));
+ }
+
+ @Test
+ public void givenAList_whenConvertWithApacheCommons2_thenReturnMapWithTheSameElements() {
+
+ Map map = convertListService.convertListWithApacheCommons2(list);
+
+ assertThat(map.values(), containsInAnyOrder(list.toArray()));
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java b/core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java
new file mode 100644
index 0000000000..348747111f
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java
@@ -0,0 +1,129 @@
+package com.baeldung.list;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.*;
+
+public class CopyListServiceUnitTest {
+
+ List flowers;
+
+ private CopyListService copyListService;
+
+ @Before
+ public void init() {
+ this.copyListService = new CopyListService();
+ this.flowers = new ArrayList<>();
+
+ Flower poppy = new Flower("Poppy", 12);
+ flowers.add(poppy);
+ Flower anemone = new Flower("Anemone", 8);
+ flowers.add(anemone);
+ Flower catmint = new Flower("Catmint", 12);
+ flowers.add(catmint);
+ Flower diascia = new Flower("Diascia", 5);
+ flowers.add(diascia);
+ Flower iris = new Flower("Iris", 3);
+ flowers.add(iris);
+ Flower pansy = new Flower("Pansy", 5);
+ flowers.add(pansy);
+ }
+
+ @Test
+ public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByConstructor() {
+ List copy = copyListService.copyListByConstructor(flowers);
+ assertEquals(copy.size(), flowers.size());
+ assertTrue(copy.containsAll(flowers));
+ }
+
+ @Test
+ public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByConstructor() {
+ List copy = copyListService.copyListByConstructorAndEditOneFlowerInTheNewList(flowers);
+ assertEquals(copy.size(), flowers.size());
+ assertTrue(copy.containsAll(flowers));
+ }
+
+ @Test
+ public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByAddAllmethod() {
+ List copy = copyListService.copyListByAddAllMethod(flowers);
+ assertEquals(copy.size(), flowers.size());
+ assertTrue(copy.containsAll(flowers));
+ }
+
+ @Test
+ public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByAddAllmethod() {
+ List copy = copyListService.copyListByAddAllMethodAndEditOneFlowerInTheNewList(flowers);
+ assertEquals(copy.size(), flowers.size());
+ assertTrue(copy.containsAll(flowers));
+ }
+
+ @Test
+ public void givenAList_whenListsHaveSameSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() {
+ List source = Arrays.asList(1,2,3);
+ List dest = Arrays.asList(4,5,6);
+
+ dest = copyListService.copyListByCopyMethod(source, dest);
+ assertEquals(dest.size(), source.size());
+ assertTrue(dest.containsAll(source));
+ }
+
+ @Test
+ public void givenAList_whenListsHaveDifferentSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() {
+ List source = Arrays.asList(1,2,3);
+ List dest = Arrays.asList(5,6,7,8,9,10);
+
+ dest = copyListService.copyListByCopyMethod(source, dest);
+ assertNotEquals(dest.size(), source.size());
+ assertTrue(dest.containsAll(source));
+ }
+
+ @Test
+ public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByStreamProcess() {
+ List copy = copyListService.copyListByStream(flowers);
+ assertEquals(copy.size(), flowers.size());
+ assertTrue(copy.containsAll(flowers));
+ }
+
+ @Test
+ public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneElementLessByStreamProcess() {
+ List copy = copyListService.copyListByStreamAndSkipFirstElement(flowers);
+ assertNotEquals(copy.size(), flowers.size());
+ assertEquals(copy.size() + 1, flowers.size());
+ assertFalse(copy.containsAll(flowers));
+ }
+
+ @Test
+ public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithFilterElementsByStreamProcess() {
+ List copy = copyListService.copyListByStreamWithFilter(flowers, 5);
+ assertNotEquals(copy.size(), flowers.size());
+ assertEquals(copy.size() + 3, flowers.size());
+ assertFalse(copy.containsAll(flowers));
+ }
+
+ @Test
+ public void givenAList_whenListIsNull_thenReturnEmptyListByStreamProcess() {
+ List copy = copyListService.copyListByStreamWithOptional(null);
+ assertNotNull(copy);
+ assertEquals(copy.size(), 0);
+ }
+
+ @Test
+ public void givenAList_whenListIsNotNull_thenReturnAnotherListWithTheElementsByStreamProcess() {
+ List copy = copyListService.copyListByStreamWithOptional(flowers);
+ assertEquals(copy.size(), flowers.size());
+ assertTrue(copy.containsAll(flowers));
+ }
+
+ @Test
+ public void givenAList_whenListIsNotNull_thenReturnAnotherListWithOneElementLessByStreamProcess() {
+ List copy = copyListService.copyListByStreamWithOptionalAndSkip(flowers);
+ assertNotEquals(copy.size(), flowers.size());
+ assertEquals(copy.size() + 1, flowers.size());
+ assertFalse(copy.containsAll(flowers));
+ }
+}
diff --git a/core-java-collections/src/test/java/com/baeldung/java/set/HashSetInitalizingUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/set/HashSetInitalizingUnitTest.java
new file mode 100644
index 0000000000..2e736501cf
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/java/set/HashSetInitalizingUnitTest.java
@@ -0,0 +1,70 @@
+package com.baeldung.java.set;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+
+public class HashSetInitalizingUnitTest {
+ @Test
+ public void whenUsingJava_usingArraysStaticMethod_thenCorrectSize() {
+ Set set = new HashSet<>(Arrays.asList("a", "b", "c"));
+ assertEquals(3, set.size());
+ }
+
+ @Test
+ public void whenUsingJava_usingAnonymousClass_thenCorrectSize() {
+ Set set = new HashSet(){{
+ add("a");
+ add("b");
+ add("c");
+ }};
+ assertEquals(3, set.size());
+ }
+
+ @Test
+ public void whenUsingJava_creatingSingletonSet_thenCorrectSize() {
+ Set set = Collections.singleton("a");
+ assertEquals(1, set.size());
+ }
+
+ public static final Set newHashSet(T... objs) {
+ Set set = new HashSet();
+ Collections.addAll(set, objs);
+ return set;
+ }
+
+ @Test
+ public void whenUsingJava_usingCustomStaticUtilMethod_thenCorrectSize() {
+ Set set = newHashSet("a","b","c");
+ assertEquals(3, set.size());
+ }
+
+ @Test
+ public void whenUsingJava8_usingCollectOnStream_thenCorrectSize() {
+ Set set = Stream.of("a", "b", "c").collect(Collectors.toCollection(HashSet::new));
+ assertEquals(3, set.size());
+ }
+
+ @Test
+ public void whenUsingGoogleGuava_createMutableSet_thenCorrectSize() {
+ Set set = Sets.newHashSet("a", "b", "c");
+ assertEquals(3, set.size());
+ }
+
+ @Test
+ public void whenUsingGoogleGuava_createImmutableSet_thenCorrectSize() {
+ Set set = ImmutableSet.of("a", "b", "c");
+ assertEquals(3, set.size());
+ }
+
+}
+
diff --git a/core-java-concurrency/pom.xml b/core-java-concurrency/pom.xml
index ae774755b6..eb81983a2a 100644
--- a/core-java-concurrency/pom.xml
+++ b/core-java-concurrency/pom.xml
@@ -75,92 +75,7 @@
-
- org.apache.maven.plugins
- maven-jar-plugin
-
-
-
- true
- libs/
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
- org.apache.maven.plugins
- maven-assembly-plugin
-
-
- package
-
- single
-
-
- ${project.basedir}
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
- jar-with-dependencies
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-shade-plugin
-
-
-
- shade
-
-
- true
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
-
-
- com.jolira
- onejar-maven-plugin
-
-
-
- org.baeldung.executable.ExecutableMavenJar
- true
- ${project.build.finalName}-onejar.${project.packaging}
-
-
- one-jar
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
- repackage
-
-
- spring-boot
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
+
diff --git a/core-java-sun/pom.xml b/core-java-sun/pom.xml
index 3233fc853e..f489f3b030 100644
--- a/core-java-sun/pom.xml
+++ b/core-java-sun/pom.xml
@@ -185,6 +185,7 @@
org.apache.maven.plugins
maven-jar-plugin
+ ${maven-jar-plugin.version}
@@ -195,79 +196,6 @@
-
- org.apache.maven.plugins
- maven-assembly-plugin
-
-
- package
-
- single
-
-
- ${project.basedir}
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
- jar-with-dependencies
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-shade-plugin
-
-
-
- shade
-
-
- true
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
-
-
- com.jolira
- onejar-maven-plugin
-
-
-
- org.baeldung.executable.ExecutableMavenJar
- true
- ${project.build.finalName}-onejar.${project.packaging}
-
-
- one-jar
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
- repackage
-
-
- spring-boot
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
org.codehaus.mojo
exec-maven-plugin
@@ -368,6 +296,7 @@
1.13
0.6.5
0.9.0
+ 4.3.4.RELEASE
3.6.1
@@ -376,7 +305,7 @@
2.19.1
1.8.0
- 4.3.4.RELEASE
+ 3.0.2
\ No newline at end of file
diff --git a/core-java/pom.xml b/core-java/pom.xml
index 6ead63cfab..c52b109f72 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -1,5 +1,5 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.baeldung
core-java
@@ -73,9 +73,10 @@
org.assertj
assertj-core
- ${assertj.version}
+ ${assertj-core.version}
test
+
commons-codec
commons-codec
@@ -146,6 +147,21 @@
icu4j
${icu4j.version}
+
+ org.apache.commons
+ commons-dbcp2
+ ${commons-dbcp2.version}
+
+
+ com.zaxxer
+ HikariCP
+ ${HikariCP.version}
+
+
+ com.mchange
+ c3p0
+ ${c3p0.version}
+
@@ -301,7 +317,7 @@
-
+
org.apache.maven.plugins
maven-javadoc-plugin
@@ -348,6 +364,7 @@
org.codehaus.mojo
exec-maven-plugin
+ ${exec-maven-plugin.version}
run-benchmarks
@@ -375,6 +392,7 @@
+
2.8.5
2.8.2
@@ -395,16 +413,23 @@
0.9.0
- 3.6.1
+ 3.10.0
+
+ 2.4.0
+ 3.2.0
+ 0.9.5.2
+
2.19.1
4.3.4.RELEASE
1.5.8.RELEASE
+
1.1
1.4.197
2.1.0.1
1.19
+
1.19
3.0.0-M1
1.5.0-b01
@@ -412,7 +437,8 @@
1.4.4
3.1.1
2.0.3.RELEASE
+ 1.6.0
61.1
-
\ No newline at end of file
+
diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java
new file mode 100644
index 0000000000..243ec88eb5
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java
@@ -0,0 +1,87 @@
+package com.baeldung.connectionpool.connectionpools;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+public class BasicConnectionPool implements ConnectionPool {
+
+ private final String url;
+ private final String user;
+ private final String password;
+ private final List connectionPool;
+ private final List usedConnections = new ArrayList<>();
+ private static final int INITIAL_POOL_SIZE = 10;
+ private final int MAX_POOL_SIZE = 20;
+
+ public static BasicConnectionPool create(String url, String user, String password) throws SQLException {
+ List pool = new ArrayList<>(INITIAL_POOL_SIZE);
+ for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
+ pool.add(createConnection(url, user, password));
+ }
+ return new BasicConnectionPool(url, user, password, pool);
+ }
+
+ private BasicConnectionPool(String url, String user, String password, List connectionPool) {
+ this.url = url;
+ this.user = user;
+ this.password = password;
+ this.connectionPool = connectionPool;
+ }
+
+ @Override
+ public Connection getConnection() throws SQLException {
+ if (connectionPool.size() == 0) {
+ if (usedConnections.size() < MAX_POOL_SIZE) {
+ connectionPool.add(createConnection(url, user, password));
+ } else {
+ throw new RuntimeException("Maximum pool size reached, no available connections!");
+ }
+ }
+
+ Connection connection = connectionPool.remove(connectionPool.size() - 1);
+ usedConnections.add(connection);
+ return connection;
+ }
+
+ @Override
+ public boolean releaseConnection(Connection connection) {
+ connectionPool.add(connection);
+ return usedConnections.remove(connection);
+ }
+
+ private static Connection createConnection(String url, String user, String password) throws SQLException {
+ return DriverManager.getConnection(url, user, password);
+ }
+
+ public int getSize() {
+ return connectionPool.size() + usedConnections.size();
+ }
+
+ @Override
+ public String getUrl() {
+ return url;
+ }
+
+ @Override
+ public String getUser() {
+ return user;
+ }
+
+ @Override
+ public String getPassword() {
+ return password;
+ }
+
+ public void shutdown() throws SQLException {
+ for (Connection c : usedConnections) {
+ this.releaseConnection(c);
+ }
+ for (Connection c : connectionPool) {
+ c.close();
+ }
+ connectionPool.clear();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java
new file mode 100644
index 0000000000..5b91f707a9
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java
@@ -0,0 +1,28 @@
+package com.baeldung.connectionpool.connectionpools;
+
+import com.mchange.v2.c3p0.ComboPooledDataSource;
+import java.beans.PropertyVetoException;
+import java.sql.Connection;
+import java.sql.SQLException;
+
+public class C3poDataSource {
+
+ private static final ComboPooledDataSource cpds = new ComboPooledDataSource();
+
+ static {
+ try {
+ cpds.setDriverClass("org.h2.Driver");
+ cpds.setJdbcUrl("jdbc:h2:mem:test");
+ cpds.setUser("user");
+ cpds.setPassword("password");
+ } catch (PropertyVetoException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static Connection getConnection() throws SQLException {
+ return cpds.getConnection();
+ }
+
+ private C3poDataSource(){}
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java
new file mode 100644
index 0000000000..3d5ad06c3d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java
@@ -0,0 +1,18 @@
+package com.baeldung.connectionpool.connectionpools;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.List;
+
+public interface ConnectionPool {
+
+ Connection getConnection() throws SQLException;
+
+ boolean releaseConnection(Connection connection);
+
+ String getUrl();
+
+ String getUser();
+
+ String getPassword();
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java
new file mode 100644
index 0000000000..2f33cde883
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java
@@ -0,0 +1,25 @@
+package com.baeldung.connectionpool.connectionpools;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import org.apache.commons.dbcp2.BasicDataSource;
+
+public class DBCPDataSource {
+
+ private static final BasicDataSource ds = new BasicDataSource();
+
+ static {
+ ds.setUrl("jdbc:h2:mem:test");
+ ds.setUsername("user");
+ ds.setPassword("password");
+ ds.setMinIdle(5);
+ ds.setMaxIdle(10);
+ ds.setMaxOpenPreparedStatements(100);
+ }
+
+ public static Connection getConnection() throws SQLException {
+ return ds.getConnection();
+ }
+
+ private DBCPDataSource(){}
+}
diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java
new file mode 100644
index 0000000000..5ed2de181d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java
@@ -0,0 +1,28 @@
+package com.baeldung.connectionpool.connectionpools;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+import java.sql.Connection;
+import java.sql.SQLException;
+
+public class HikariCPDataSource {
+
+ private static final HikariConfig config = new HikariConfig();
+ private static final HikariDataSource ds;
+
+ static {
+ config.setJdbcUrl("jdbc:h2:mem:test");
+ config.setUsername("user");
+ config.setPassword("password");
+ config.addDataSourceProperty("cachePrepStmts", "true");
+ config.addDataSourceProperty("prepStmtCacheSize", "250");
+ config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
+ ds = new HikariDataSource(config);
+ }
+
+ public static Connection getConnection() throws SQLException {
+ return ds.getConnection();
+ }
+
+ private HikariCPDataSource(){}
+}
diff --git a/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java b/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java
new file mode 100644
index 0000000000..5edc6bba94
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java
@@ -0,0 +1,69 @@
+package com.baeldung.connectionpool;
+
+import com.baeldung.connectionpool.connectionpools.BasicConnectionPool;
+import com.baeldung.connectionpool.connectionpools.ConnectionPool;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.List;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class BasicConnectionPoolUnitTest {
+
+ private static ConnectionPool connectionPool;
+
+ @BeforeClass
+ public static void setUpBasicConnectionPoolInstance() throws SQLException {
+ connectionPool = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
+ }
+
+ @Test
+ public void givenBasicConnectionPoolInstance_whenCalledgetConnection_thenCorrect() throws Exception {
+ assertTrue(connectionPool.getConnection().isValid(1));
+ }
+
+ @Test
+ public void givenBasicConnectionPoolInstance_whenCalledreleaseConnection_thenCorrect() throws Exception {
+ Connection connection = connectionPool.getConnection();
+ assertThat(connectionPool.releaseConnection(connection)).isTrue();
+ }
+
+ @Test
+ public void givenBasicConnectionPoolInstance_whenCalledgetUrl_thenCorrect() {
+ assertThat(connectionPool.getUrl()).isEqualTo("jdbc:h2:mem:test");
+ }
+
+ @Test
+ public void givenBasicConnectionPoolInstance_whenCalledgetUser_thenCorrect() {
+ assertThat(connectionPool.getUser()).isEqualTo("user");
+ }
+
+ @Test
+ public void givenBasicConnectionPoolInstance_whenCalledgetPassword_thenCorrect() {
+ assertThat(connectionPool.getPassword()).isEqualTo("password");
+ }
+
+ @Test(expected = RuntimeException.class)
+ public void givenBasicConnectionPoolInstance_whenAskedForMoreThanMax_thenError() throws Exception {
+ // this test needs to be independent so it doesn't share the same connection pool as other tests
+ ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
+ final int MAX_POOL_SIZE = 20;
+ for (int i = 0; i < MAX_POOL_SIZE + 1; i++) {
+ cp.getConnection();
+ }
+ fail();
+ }
+
+ @Test
+ public void givenBasicConnectionPoolInstance_whenSutdown_thenEmpty() throws Exception {
+ ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
+ assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(10);
+
+ ((BasicConnectionPool) cp).shutdown();
+ assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(0);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java b/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java
new file mode 100644
index 0000000000..a02daa40f6
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java
@@ -0,0 +1,14 @@
+package com.baeldung.connectionpool;
+
+import com.baeldung.connectionpool.connectionpools.C3poDataSource;
+import java.sql.SQLException;
+import static org.junit.Assert.assertTrue;
+import org.junit.Test;
+
+public class C3poDataSourceUnitTest {
+
+ @Test
+ public void givenC3poDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
+ assertTrue(C3poDataSource.getConnection().isValid(1));
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java b/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java
new file mode 100644
index 0000000000..9583eedf4b
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java
@@ -0,0 +1,14 @@
+package com.baeldung.connectionpool;
+
+import com.baeldung.connectionpool.connectionpools.DBCPDataSource;
+import java.sql.SQLException;
+import static org.junit.Assert.assertTrue;
+import org.junit.Test;
+
+public class DBCPDataSourceUnitTest {
+
+ @Test
+ public void givenDBCPDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
+ assertTrue(DBCPDataSource.getConnection().isValid(1));
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java b/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java
new file mode 100644
index 0000000000..6b78815797
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java
@@ -0,0 +1,14 @@
+package com.baeldung.connectionpool;
+
+import com.baeldung.connectionpool.connectionpools.HikariCPDataSource;
+import java.sql.SQLException;
+import static org.junit.Assert.assertTrue;
+import org.junit.Test;
+
+public class HikariCPDataSourceUnitTest {
+
+ @Test
+ public void givenHikariDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
+ assertTrue(HikariCPDataSource.getConnection().isValid(1));
+ }
+}
\ No newline at end of file
diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml
index fa16dad496..afa7d8a963 100644
--- a/core-kotlin/pom.xml
+++ b/core-kotlin/pom.xml
@@ -60,7 +60,6 @@
org.jetbrains.kotlin
kotlin-reflect
${kotlin-reflect.version}
- test
org.jetbrains.kotlinx
@@ -224,10 +223,11 @@
- 1.2.41
- 1.2.41
- 1.2.41
- 1.2.41
+ UTF-8
+ 1.2.51
+ 1.2.51
+ 1.2.51
+ 1.2.51
0.22.5
0.9.2
1.5.0
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnAny.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnAny.kt
new file mode 100644
index 0000000000..32d968fff5
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnAny.kt
@@ -0,0 +1,30 @@
+package com.baeldung.kotlin.logging
+
+import org.slf4j.Logger
+
+open class LoggerAsExtensionOnAny {
+ val logger = logger()
+
+ fun log(s: String) {
+ logger().info(s)
+ logger.info(s)
+ }
+}
+
+class ExtensionSubclass : LoggerAsExtensionOnAny()
+
+fun T.logger(): Logger = getLogger(getClassForLogging(javaClass))
+
+fun main(args: Array) {
+ LoggerAsExtensionOnAny().log("test")
+ ExtensionSubclass().log("sub")
+ "foo".logger().info("foo")
+ 1.logger().info("uh-oh!")
+ SomeOtherClass().logger()
+}
+
+class SomeOtherClass {
+ fun logger(): String {
+ return "foo"
+ }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnMarkerInterface.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnMarkerInterface.kt
new file mode 100644
index 0000000000..b33d4c9f93
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnMarkerInterface.kt
@@ -0,0 +1,30 @@
+package com.baeldung.kotlin.logging
+
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+interface Logging
+
+inline fun T.logger(): Logger =
+ //Wrong logger name!
+ //LoggerFactory.getLogger(javaClass.name + " w/interface")
+ LoggerFactory.getLogger(getClassForLogging(T::class.java).name + " w/interface")
+
+open class LoggerAsExtensionOnMarkerInterface : Logging {
+ companion object : Logging {
+ val logger = logger()
+ }
+
+ fun log(s: String) {
+ logger().info(s)
+ logger.info(s)
+ }
+}
+
+class MarkerExtensionSubclass : LoggerAsExtensionOnMarkerInterface()
+
+fun main(args: Array) {
+ LoggerAsExtensionOnMarkerInterface().log("test")
+ MarkerExtensionSubclass().log("sub")
+ "foo".logger().info("foo")
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsProperty.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsProperty.kt
new file mode 100644
index 0000000000..979b3b3a10
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsProperty.kt
@@ -0,0 +1,17 @@
+package com.baeldung.kotlin.logging
+
+open class LoggerAsProperty {
+ private val logger = getLogger(javaClass)
+
+ fun log(s: String) {
+ logger.info(s)
+ }
+
+}
+
+class PropertySubclass : LoggerAsProperty()
+
+fun main(args: Array) {
+ LoggerAsProperty().log("test")
+ PropertySubclass().log("sub")
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsPropertyDelegate.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsPropertyDelegate.kt
new file mode 100644
index 0000000000..23f04722be
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsPropertyDelegate.kt
@@ -0,0 +1,47 @@
+package com.baeldung.kotlin.logging
+
+import org.slf4j.Logger
+import kotlin.properties.ReadOnlyProperty
+import kotlin.reflect.KProperty
+
+open class LoggerAsPropertyDelegate {
+ private val lazyLogger by lazyLogger()
+ protected val logger by LoggerDelegate()
+ private val logger2 = logger
+
+ companion object {
+ private val lazyLoggerComp by lazyLogger()
+ private val loggerComp by LoggerDelegate()
+ }
+
+ open fun log(s: String) {
+ logger.info(s)
+ logger2.info(s)
+ lazyLogger.info(s)
+ loggerComp.info(s)
+ lazyLoggerComp.info(s)
+ }
+
+}
+
+class DelegateSubclass : LoggerAsPropertyDelegate() {
+ override fun log(s: String) {
+ logger.info("-- in sub")
+ super.log(s)
+ }
+}
+
+fun lazyLogger(forClass: Class<*>): Lazy =
+ lazy { getLogger(getClassForLogging(forClass)) }
+
+fun T.lazyLogger(): Lazy = lazyLogger(javaClass)
+
+fun main(args: Array) {
+ LoggerAsPropertyDelegate().log("test")
+ DelegateSubclass().log("sub")
+}
+
+class LoggerDelegate : ReadOnlyProperty {
+ override fun getValue(thisRef: R, property: KProperty<*>) =
+ getLogger(getClassForLogging(thisRef.javaClass))
+}
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerInCompanionObject.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerInCompanionObject.kt
new file mode 100644
index 0000000000..f973606369
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerInCompanionObject.kt
@@ -0,0 +1,44 @@
+package com.baeldung.kotlin.logging
+
+open class LoggerInCompanionObject {
+ companion object {
+ private val loggerWithExplicitClass = getLogger(LoggerInCompanionObject::class.java)
+ @Suppress("JAVA_CLASS_ON_COMPANION")
+ private val loggerWithWrongClass = getLogger(javaClass)
+ @Suppress("JAVA_CLASS_ON_COMPANION")
+ private val logger = getLogger(javaClass.enclosingClass)
+ }
+
+ fun log(s: String) {
+ loggerWithExplicitClass.info(s)
+ loggerWithWrongClass.info(s)
+ logger.info(s)
+ }
+
+ class Inner {
+ companion object {
+ private val loggerWithExplicitClass = getLogger(Inner::class.java)
+ @Suppress("JAVA_CLASS_ON_COMPANION")
+ @JvmStatic
+ private val loggerWithWrongClass = getLogger(javaClass)
+ @Suppress("JAVA_CLASS_ON_COMPANION")
+ @JvmStatic
+ private val logger = getLogger(javaClass.enclosingClass)
+ }
+
+ fun log(s: String) {
+ loggerWithExplicitClass.info(s)
+ loggerWithWrongClass.info(s)
+ logger.info(s)
+ }
+ }
+
+}
+
+class CompanionSubclass : LoggerInCompanionObject()
+
+fun main(args: Array) {
+ LoggerInCompanionObject().log("test")
+ LoggerInCompanionObject.Inner().log("test")
+ CompanionSubclass().log("sub")
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/Util.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/Util.kt
new file mode 100644
index 0000000000..b9c0d9e34c
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/Util.kt
@@ -0,0 +1,13 @@
+package com.baeldung.kotlin.logging
+
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import kotlin.reflect.full.companionObject
+
+fun getLogger(forClass: Class<*>): Logger = LoggerFactory.getLogger(forClass)
+
+fun getClassForLogging(javaClass: Class): Class<*> {
+ return javaClass.enclosingClass?.takeIf {
+ it.kotlin.companionObject?.java == javaClass
+ } ?: javaClass
+}
\ No newline at end of file
diff --git a/disruptor/pom.xml b/disruptor/pom.xml
index 039d7f9c2d..6f3a8d9bfd 100644
--- a/disruptor/pom.xml
+++ b/disruptor/pom.xml
@@ -55,6 +55,7 @@
org.apache.maven.plugins
maven-jar-plugin
+ ${maven-jar-plugin.version}
@@ -91,6 +92,7 @@
org.apache.maven.plugins
maven-shade-plugin
+ ${maven-shade-plugin.version}
@@ -133,6 +135,9 @@
6.10
3.6.1
+
+ 2.4.3
+ 3.0.2
\ No newline at end of file
diff --git a/ejb/ejb-remote/pom.xml b/ejb/ejb-remote/pom.xml
index d25df0cfc9..fffbbdb1da 100755
--- a/ejb/ejb-remote/pom.xml
+++ b/ejb/ejb-remote/pom.xml
@@ -74,7 +74,7 @@
9990
testUser
admin1234!
- ${build.finalName}.jar
+ ${project.build.finalName}.jar
diff --git a/geotools/pom.xml b/geotools/pom.xml
index 273b14b538..3ac8a63564 100644
--- a/geotools/pom.xml
+++ b/geotools/pom.xml
@@ -1,61 +1,62 @@
-
- 4.0.0
- com.baeldung
- geotools
- 0.0.1-SNAPSHOT
- jar
- geotools
- http://maven.apache.org
+
+ 4.0.0
+ geotools
+ 0.0.1-SNAPSHOT
+ jar
+ geotools
+ http://maven.apache.org
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
-
-
- org.geotools
- gt-shapefile
- ${geotools-shapefile.version}
-
-
- org.geotools
- gt-epsg-hsql
- ${geotools.version}
-
-
- org.geotools
- gt-swing
- ${geotools-swing.version}
-
-
+
+
+ org.geotools
+ gt-shapefile
+ ${geotools-shapefile.version}
+
+
+ org.geotools
+ gt-epsg-hsql
+ ${geotools.version}
+
+
+ org.geotools
+ gt-swing
+ ${geotools-swing.version}
+
+
-
-
- maven2-repository.dev.java.net
- Java.net repository
- http://download.java.net/maven/2
-
-
- osgeo
- Open Source Geospatial Foundation Repository
- http://download.osgeo.org/webdav/geotools/
-
-
-
- true
-
- opengeo
- OpenGeo Maven Repository
- http://repo.opengeo.org
-
-
+
+
+ maven2-repository.dev.java.net
+ Java.net repository
+ http://download.java.net/maven/2
+
+
+ osgeo
+ Open Source Geospatial Foundation Repository
+ http://download.osgeo.org/webdav/geotools/
+
+
+
+ true
+
+ opengeo
+ OpenGeo Maven Repository
+ http://repo.opengeo.org
+
+
+
+
+ 15.2
+ 15.2
+ 15.2
+
-
- 15.2
- 15.2
- 15.2
-
diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml
index d96a589e32..e392ce4e8c 100644
--- a/google-web-toolkit/pom.xml
+++ b/google-web-toolkit/pom.xml
@@ -1,116 +1,118 @@
-
+
-
- 4.0.0
- com.baeldung
- google_web_toolkit
- war
- 1.0-SNAPSHOT
- com.baeldung.Google_web_toolkit
+
+ 4.0.0
+ com.baeldung
+ google-web-toolkit
+ war
+ 1.0-SNAPSHOT
-
+
+
+
+
+ com.google.gwt
+ gwt
+ 2.8.2
+ pom
+ import
+
+
+
-
- 1.8
- 1.8
+
+
+ com.google.gwt
+ gwt-servlet
+ runtime
+
+
+ com.google.gwt
+ gwt-user
+ provided
+
+
+ com.google.gwt
+ gwt-dev
+ provided
+
+
+ junit
+ junit
+ 4.11
+ test
+
+
-
- UTF-8
- UTF-8
-
+
+
+ ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
-
-
- com.google.gwt
- gwt
- 2.8.2
- pom
- import
-
-
-
+
-
-
- com.google.gwt
- gwt-servlet
- runtime
-
-
- com.google.gwt
- gwt-user
- provided
-
-
- com.google.gwt
- gwt-dev
- provided
-
-
- junit
- junit
- 4.11
- test
-
-
+
+
+ net.ltgt.gwt.maven
+ gwt-maven-plugin
+ 1.0-rc-8
+
+
+
+ compile
+ test
+
+
+
+
+ com.baeldung.Google_web_toolkit
+ Google_web_toolkit
+ true
+
+ 1.8
+
+
+
+ -compileReport
+ -XcompilerMetrics
+
+
+ ${project.build.directory}/${project.build.finalName}
+ compile+runtime
+
+
+ Google_web_toolkit.html
+
+
+
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
+
+
+ maven-surefire-plugin
+ 2.17
+
+ true
+
+
-
+
+
+
+
-
-
- net.ltgt.gwt.maven
- gwt-maven-plugin
- 1.0-rc-8
-
-
-
- compile
- test
-
-
-
-
- com.baeldung.Google_web_toolkit
- Google_web_toolkit
- true
-
- 1.8
-
-
-
- -compileReport
- -XcompilerMetrics
-
-
- ${project.build.directory}/${project.build.finalName}
- compile+runtime
-
-
- Google_web_toolkit.html
-
-
-
+
+ 1.8
+ 1.8
-
-
- maven-surefire-plugin
- 2.17
-
- true
-
-
-
-
-
+
+ UTF-8
+ UTF-8
+
+
diff --git a/hibernate5/pom.xml b/hibernate5/pom.xml
index cf7ed90cee..610c893bdc 100644
--- a/hibernate5/pom.xml
+++ b/hibernate5/pom.xml
@@ -5,8 +5,6 @@
com.baeldung
hibernate5
0.0.1-SNAPSHOT
- hibernate5
- http://maven.apache.org
com.baeldung
@@ -59,9 +57,6 @@
- UTF-8
-
- 3.7.0
5.3.2.Final
6.0.6
2.2.3
diff --git a/hibernate5/src/main/resources/logback.xml b/hibernate5/src/main/resources/logback.xml
new file mode 100644
index 0000000000..d87a87bf53
--- /dev/null
+++ b/hibernate5/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %date [%thread] %-5level %logger{36} - %message%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml
index 304531d684..5490cd40f7 100644
--- a/java-ee-8-security-api/pom.xml
+++ b/java-ee-8-security-api/pom.xml
@@ -3,32 +3,27 @@
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">
4.0.0
-
com.baeldung
java-ee-8-security-api
1.0-SNAPSHOT
pom
-
- app-auth-basic-store-db
- app-auth-form-store-ldap
- app-auth-custom-form-store-custom
- app-auth-custom-no-store
-
-
+
javax
javaee-web-api
${javaee-version}
provided
+
maven-war-plugin
+ ${maven-war-plugin.version}
false
pom.xml
@@ -69,6 +64,15 @@
2.3
18.0.0.1
1.4.197
+
+ 3.2.2
+
+ app-auth-basic-store-db
+ app-auth-form-store-ldap
+ app-auth-custom-form-store-custom
+ app-auth-custom-no-store
+
+
diff --git a/java-numbers/pom.xml b/java-numbers/pom.xml
index d1517fa57a..a9fb556517 100644
--- a/java-numbers/pom.xml
+++ b/java-numbers/pom.xml
@@ -100,102 +100,6 @@
-
- org.apache.maven.plugins
- maven-jar-plugin
- ${maven-jar-plugin.version}
-
-
-
- true
- libs/
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-assembly-plugin
-
-
- package
-
- single
-
-
- ${project.basedir}
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
- jar-with-dependencies
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-shade-plugin
- ${maven-shade-plugin.version}
-
-
-
- shade
-
-
- true
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
-
-
-
- com.jolira
- onejar-maven-plugin
- ${onejar-maven-plugin.version}
-
-
-
- org.baeldung.executable.ExecutableMavenJar
- true
- ${project.build.finalName}-onejar.${project.packaging}
-
-
- one-jar
-
-
-
-
-
-
- org.codehaus.mojo
- exec-maven-plugin
- ${exec-maven-plugin.version}
-
- java
- com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
-
- -Xmx300m
- -XX:+UseParallelGC
- -classpath
-
- com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
-
-
-
-
org.apache.maven.plugins
maven-javadoc-plugin
@@ -235,31 +139,6 @@
-
- org.codehaus.mojo
- exec-maven-plugin
-
-
-
- run-benchmarks
-
- none
-
- exec
-
-
- test
- java
-
- -classpath
-
- org.openjdk.jmh.Main
- .*
-
-
-
-
-
@@ -280,7 +159,5 @@
2.19.1
3.0.0-M1
3.0.2
- 1.4.4
- 3.1.1
diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml
index 6ac756c807..0536f80ada 100644
--- a/jhipster/jhipster-monolithic/pom.xml
+++ b/jhipster/jhipster-monolithic/pom.xml
@@ -6,7 +6,7 @@
jhipster-monolithic
0.0.1-SNAPSHOT
war
- JHipster Monolithic Application
+ JHipster Monolithic Application
parent-boot-1
diff --git a/jhipster/jhipster-monolithic/src/main/resources/logback-spring.xml b/jhipster/jhipster-monolithic/src/main/resources/logback-spring.xml
index 3c62a70c31..2fda7cc968 100644
--- a/jhipster/jhipster-monolithic/src/main/resources/logback-spring.xml
+++ b/jhipster/jhipster-monolithic/src/main/resources/logback-spring.xml
@@ -3,28 +3,9 @@
-
-
-
-
-
-
+
diff --git a/jmh/pom.xml b/jmh/pom.xml
index 45ad0d426f..1e01809fe6 100644
--- a/jmh/pom.xml
+++ b/jmh/pom.xml
@@ -33,6 +33,7 @@
org.apache.maven.plugins
maven-jar-plugin
+ ${maven-jar-plugin.version}
@@ -46,6 +47,7 @@
1.19
+ 3.0.2
\ No newline at end of file
diff --git a/jnosql/jnosql-artemis/pom.xml b/jnosql/jnosql-artemis/pom.xml
new file mode 100644
index 0000000000..6186b3510c
--- /dev/null
+++ b/jnosql/jnosql-artemis/pom.xml
@@ -0,0 +1,88 @@
+
+
+ 4.0.0
+
+
+ com.baeldung.jnosql
+ jnosql
+ 1.0-SNAPSHOT
+
+
+ jnosql-artemis
+ war
+
+
+ 2.4.2
+ false
+
+
+
+ ${artifactId}
+
+
+ net.wasdev.wlp.maven.plugins
+ liberty-maven-plugin
+ ${liberty-maven-plugin.version}
+
+
+ io.openliberty
+ openliberty-webProfile8
+ RELEASE
+ zip
+
+ project
+ true
+ src/main/liberty/config/server.xml
+
+
+
+ install-server
+ prepare-package
+
+ install-server
+ create-server
+ install-feature
+
+
+
+ install-apps
+ package
+
+ install-apps
+
+
+
+
+
+
+
+
+
+
+ javax
+ javaee-web-api
+ 8.0
+ provided
+
+
+
+ org.jnosql.artemis
+ artemis-configuration
+ ${jnosql.version}
+
+
+ org.jnosql.artemis
+ artemis-document
+ ${jnosql.version}
+
+
+ org.jnosql.diana
+ mongodb-driver
+ ${jnosql.version}
+
+
+
+
+
diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/AppConfig.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/AppConfig.java
new file mode 100644
index 0000000000..bf445d9d01
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/AppConfig.java
@@ -0,0 +1,10 @@
+package com.baeldung.jnosql.artemis;
+
+import javax.enterprise.context.Initialized;
+import javax.enterprise.event.Observes;
+import javax.ws.rs.ApplicationPath;
+import javax.ws.rs.core.Application;
+
+@ApplicationPath("")
+public class AppConfig extends Application {
+}
diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EmbeddedMongoDBSetup.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EmbeddedMongoDBSetup.java
new file mode 100644
index 0000000000..8b3e161f85
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EmbeddedMongoDBSetup.java
@@ -0,0 +1,52 @@
+package com.baeldung.jnosql.artemis;
+
+import de.flapdoodle.embed.mongo.MongodExecutable;
+import de.flapdoodle.embed.mongo.MongodProcess;
+import de.flapdoodle.embed.mongo.MongodStarter;
+import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
+import de.flapdoodle.embed.mongo.config.Net;
+import de.flapdoodle.embed.mongo.distribution.Version;
+import de.flapdoodle.embed.process.runtime.Network;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.context.Destroyed;
+import javax.enterprise.context.Initialized;
+import javax.enterprise.event.Observes;
+import java.io.IOException;
+
+@ApplicationScoped
+public class EmbeddedMongoDBSetup {
+
+ private static final String MONGODB_HOST = "localhost";
+ private static final int MONGODB_PORT = 27019;
+
+ private static final MongodStarter starter = MongodStarter.getDefaultInstance();
+ private static MongodExecutable _mongodExe;
+ private static MongodProcess _mongod;
+
+ public void init(@Observes @Initialized(ApplicationScoped.class) Object init) {
+ try {
+ System.out.println("Starting Embedded MongoDB");
+ initdb();
+ System.out.println("Embedded MongoDB started");
+ } catch (IOException e) {
+ System.out.println("Embedded MongoDB starting error !!");
+ e.printStackTrace();
+ }
+ }
+
+ private void initdb() throws IOException {
+ _mongodExe = starter.prepare(new MongodConfigBuilder()
+ .version(Version.Main.DEVELOPMENT)
+ .net(new Net(MONGODB_HOST, MONGODB_PORT, Network.localhostIsIPv6()))
+ .build());
+ _mongod = _mongodExe.start();
+ }
+
+ public void destroy(@Observes @Destroyed(ApplicationScoped.class) Object init) {
+ System.out.println("Stopping Embedded MongoDB");
+ _mongod.stop();
+ _mongodExe.stop();
+ System.out.println("Embedded MongoDB stopped !");
+ }
+}
diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EntityManagerProducer.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EntityManagerProducer.java
new file mode 100644
index 0000000000..c51868886b
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EntityManagerProducer.java
@@ -0,0 +1,33 @@
+package com.baeldung.jnosql.artemis;
+
+import org.jnosql.artemis.ConfigurationUnit;
+import org.jnosql.diana.api.document.DocumentCollectionManager;
+import org.jnosql.diana.api.document.DocumentCollectionManagerFactory;
+import org.jnosql.diana.mongodb.document.MongoDBDocumentCollectionManager;
+import org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration;
+
+import javax.annotation.PostConstruct;
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.inject.Disposes;
+import javax.enterprise.inject.Produces;
+import javax.inject.Inject;
+
+@ApplicationScoped
+public class EntityManagerProducer {
+
+ private static final String DATABASE = "todos";
+
+ @Inject
+ @ConfigurationUnit(name = "document")
+ private DocumentCollectionManagerFactory managerFactory;
+
+ @Produces
+ public DocumentCollectionManager getEntityManager() {
+ return managerFactory.get(DATABASE);
+ }
+
+ public void close(@Disposes DocumentCollectionManager entityManager) {
+ entityManager.close();
+ }
+
+}
diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/RepositoryTodoManager.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/RepositoryTodoManager.java
new file mode 100644
index 0000000000..2b19858f6d
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/RepositoryTodoManager.java
@@ -0,0 +1,41 @@
+package com.baeldung.jnosql.artemis;
+
+import com.baeldung.jnosql.artemis.qualifier.Repo;
+import org.jnosql.artemis.Database;
+import org.jnosql.artemis.DatabaseType;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import java.util.List;
+import java.util.Optional;
+
+@ApplicationScoped
+@Repo
+public class RepositoryTodoManager implements TodoManager {
+
+ @Inject
+ @Database(DatabaseType.DOCUMENT)
+ private TodoRepository repository;
+
+ @Override
+ public Todo add(Todo todo) {
+ return repository.save(todo);
+ }
+
+ @Override
+ public Todo get(String id) {
+ Optional todo = repository.findById(id);
+ return todo.get();
+ }
+
+ @Override
+ public List getAll() {
+ return repository.findAll();
+ }
+
+ @Override
+ public void delete(String id) {
+ repository.deleteById(id);
+ }
+
+}
diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TemplateTodoManager.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TemplateTodoManager.java
new file mode 100644
index 0000000000..8c9ce745f7
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TemplateTodoManager.java
@@ -0,0 +1,43 @@
+package com.baeldung.jnosql.artemis;
+
+import com.baeldung.jnosql.artemis.qualifier.Template;
+import org.jnosql.artemis.document.DocumentTemplate;
+import org.jnosql.diana.api.document.DocumentQuery;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import java.util.List;
+import java.util.Optional;
+
+import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select;
+
+@ApplicationScoped
+@Template
+public class TemplateTodoManager implements TodoManager {
+
+ @Inject
+ private DocumentTemplate documentTemplate;
+
+ @Override
+ public Todo add(Todo todo) {
+ return documentTemplate.insert(todo);
+ }
+
+ @Override
+ public Todo get(String id) {
+ Optional todo = documentTemplate.find(Todo.class, id);
+ return todo.get();
+ }
+
+ @Override
+ public List getAll() {
+ DocumentQuery query = select().from("Todo").build();
+ return documentTemplate.select(query);
+ }
+
+ @Override
+ public void delete(String id) {
+ documentTemplate.delete(Todo.class, id);
+ }
+
+}
diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/Todo.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/Todo.java
new file mode 100644
index 0000000000..f250ddfa66
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/Todo.java
@@ -0,0 +1,51 @@
+package com.baeldung.jnosql.artemis;
+
+import org.jnosql.artemis.Column;
+import org.jnosql.artemis.Entity;
+import org.jnosql.artemis.Id;
+
+import java.io.Serializable;
+
+@Entity
+public class Todo implements Serializable {
+
+ @Id("id")
+ public String id;
+ @Column
+ public String name;
+ @Column
+ public String description;
+
+ public Todo() {
+ }
+
+ public Todo(String id, String name, String description) {
+ this.id = id;
+ this.name = name;
+ this.description = description;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+}
diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoManager.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoManager.java
new file mode 100644
index 0000000000..cdcfea5b40
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoManager.java
@@ -0,0 +1,14 @@
+package com.baeldung.jnosql.artemis;
+
+import java.util.List;
+
+public interface TodoManager {
+
+ Todo add(Todo todo);
+
+ Todo get(String id);
+
+ List getAll();
+
+ void delete(String id);
+}
diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoRepository.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoRepository.java
new file mode 100644
index 0000000000..52381d1757
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoRepository.java
@@ -0,0 +1,10 @@
+package com.baeldung.jnosql.artemis;
+
+import org.jnosql.artemis.Repository;
+
+import java.util.List;
+
+public interface TodoRepository extends Repository {
+ List findByName(String name);
+ List findAll();
+}
diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoResource.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoResource.java
new file mode 100644
index 0000000000..42149af3cc
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoResource.java
@@ -0,0 +1,48 @@
+package com.baeldung.jnosql.artemis;
+
+import com.baeldung.jnosql.artemis.qualifier.Repo;
+import com.baeldung.jnosql.artemis.qualifier.Template;
+
+import javax.inject.Inject;
+import javax.ws.rs.*;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+
+@Path("todos")
+public class TodoResource {
+
+ /*
+ Use eiher @Template or @Repo
+ */
+ @Inject
+ @Template
+ //@Repo
+ private TodoManager todoManager;
+
+ @GET
+ @Path("")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response all() {
+ return Response.ok(todoManager.getAll()).build();
+ }
+
+ @GET
+ @Path("{id}")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response get(@PathParam("id") String id) {
+ Todo todo = todoManager.get(id);
+ return Response.ok(todo).build();
+ }
+
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ public Response add(Todo todo) {
+ Todo savedTodo = todoManager.add(todo);
+ System.out.println(savedTodo.id);
+ return Response.created(
+ UriBuilder.fromResource(this.getClass()).path(String.valueOf(savedTodo.id)).build())
+ .build();
+ }
+
+}
diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Repo.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Repo.java
new file mode 100644
index 0000000000..a5883946db
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Repo.java
@@ -0,0 +1,13 @@
+package com.baeldung.jnosql.artemis.qualifier;
+
+import javax.inject.Qualifier;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.FIELD, ElementType.TYPE})
+@Qualifier
+public @interface Repo {
+}
\ No newline at end of file
diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Template.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Template.java
new file mode 100644
index 0000000000..81fbbe5271
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Template.java
@@ -0,0 +1,13 @@
+package com.baeldung.jnosql.artemis.qualifier;
+
+import javax.inject.Qualifier;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.FIELD, ElementType.TYPE})
+@Qualifier
+public @interface Template {
+}
\ No newline at end of file
diff --git a/jnosql/jnosql-artemis/src/main/liberty/config/server.xml b/jnosql/jnosql-artemis/src/main/liberty/config/server.xml
new file mode 100644
index 0000000000..897aca853a
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/liberty/config/server.xml
@@ -0,0 +1,6 @@
+
+
+ webProfile-8.0
+
+
+
diff --git a/jnosql/jnosql-artemis/src/main/resources/META-INF/beans.xml b/jnosql/jnosql-artemis/src/main/resources/META-INF/beans.xml
new file mode 100644
index 0000000000..4f0b3cdeeb
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/resources/META-INF/beans.xml
@@ -0,0 +1,6 @@
+
+
\ No newline at end of file
diff --git a/jnosql/jnosql-artemis/src/main/resources/META-INF/jnosql.json b/jnosql/jnosql-artemis/src/main/resources/META-INF/jnosql.json
new file mode 100644
index 0000000000..b8e26cf54a
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/resources/META-INF/jnosql.json
@@ -0,0 +1,10 @@
+[
+ {
+ "description": "The mongodb document configuration",
+ "name": "document",
+ "provider": "org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration",
+ "settings": {
+ "mongodb-server-host-1":"localhost:27019"
+ }
+ }
+]
\ No newline at end of file
diff --git a/jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json b/jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json
new file mode 100644
index 0000000000..b8e26cf54a
--- /dev/null
+++ b/jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json
@@ -0,0 +1,10 @@
+[
+ {
+ "description": "The mongodb document configuration",
+ "name": "document",
+ "provider": "org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration",
+ "settings": {
+ "mongodb-server-host-1":"localhost:27019"
+ }
+ }
+]
\ No newline at end of file
diff --git a/jnosql/jnosql-diana/pom.xml b/jnosql/jnosql-diana/pom.xml
new file mode 100644
index 0000000000..767defb2a8
--- /dev/null
+++ b/jnosql/jnosql-diana/pom.xml
@@ -0,0 +1,93 @@
+
+
+ 4.0.0
+
+
+ com.baeldung.jnosql
+ jnosql
+ 1.0-SNAPSHOT
+
+
+ jnosql-diana
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ 1.6.0
+
+
+ document
+
+ java
+
+
+ com.baeldung.jnosql.diana.document.DocumentApp
+
+
+
+ column
+
+ java
+
+
+ com.baeldung.jnosql.diana.column.ColumnFamilyApp
+
+
+
+ key
+
+ java
+
+
+ com.baeldung.jnosql.diana.key.KeyValueApp
+
+
+
+
+
+
+
+
+
+
+
+ org.jnosql.diana
+ diana-document
+ 0.0.5
+
+
+ org.jnosql.diana
+ mongodb-driver
+ 0.0.5
+
+
+
+
+ org.jnosql.diana
+ diana-column
+ 0.0.5
+
+
+ org.jnosql.diana
+ cassandra-driver
+ 0.0.5
+
+
+
+
+ org.jnosql.diana
+ diana-key-value
+ 0.0.5
+
+
+ org.jnosql.diana
+ hazelcast-driver
+ 0.0.5
+
+
+
+
\ No newline at end of file
diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/column/ColumnFamilyApp.java b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/column/ColumnFamilyApp.java
new file mode 100644
index 0000000000..5b65f9ad73
--- /dev/null
+++ b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/column/ColumnFamilyApp.java
@@ -0,0 +1,32 @@
+package com.baeldung.jnosql.diana.column;
+
+import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
+import org.jnosql.diana.api.column.*;
+import org.jnosql.diana.cassandra.column.CassandraConfiguration;
+
+public class ColumnFamilyApp {
+
+ private static final String KEY_SPACE = "myKeySpace";
+ private static final String COLUMN_FAMILY = "books";
+
+ public static void main(String... args) throws Exception {
+
+ EmbeddedCassandraServerHelper.startEmbeddedCassandra();
+
+ ColumnConfiguration configuration = new CassandraConfiguration();
+ try(ColumnFamilyManagerFactory entityManagerFactory = configuration.get()) {
+ ColumnFamilyManager entityManager = entityManagerFactory.get(KEY_SPACE);
+ ColumnEntity columnEntity = ColumnEntity.of(COLUMN_FAMILY);
+ Column key = Columns.of("id", 10L);
+ Column name = Columns.of("name", "JNoSQL in Acion");
+ columnEntity.add(key);
+ columnEntity.add(name);
+ ColumnEntity saved = entityManager.insert(columnEntity);
+ System.out.println(saved);
+ }
+
+ EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
+ EmbeddedCassandraServerHelper.stopEmbeddedCassandra();
+ }
+
+}
diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/DocumentApp.java b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/DocumentApp.java
new file mode 100644
index 0000000000..258c812a31
--- /dev/null
+++ b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/DocumentApp.java
@@ -0,0 +1,67 @@
+package com.baeldung.jnosql.diana.document;
+
+import org.jnosql.diana.api.Settings;
+import org.jnosql.diana.api.document.*;
+import org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.delete;
+import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select;
+
+public class DocumentApp {
+
+ private static final String DB_NAME = "my-db";
+ private static final String DOCUMENT_COLLECTION = "books";
+
+ public static final String KEY_NAME = "_id";
+
+ DocumentConfiguration configuration = new MongoDBDocumentConfiguration();
+
+ public static void main(String... args) throws Exception {
+ MongoDbInit.startMongoDb();
+
+ DocumentApp app = new DocumentApp();
+ app.process();
+
+ MongoDbInit.stopMongoDb();
+ }
+
+ public void process() {
+
+ Map map = new HashMap<>();
+ map.put("mongodb-server-host-1", "localhost:27017");
+
+ try (DocumentCollectionManagerFactory managerFactory = configuration.get(Settings.of(map));
+ DocumentCollectionManager manager = managerFactory.get(DB_NAME);) {
+
+ DocumentEntity documentEntity = DocumentEntity.of(DOCUMENT_COLLECTION);
+ documentEntity.add(Document.of(KEY_NAME, "100"));
+ documentEntity.add(Document.of("name", "JNoSQL in Action"));
+ documentEntity.add(Document.of("pages", 620));
+
+ //CREATE
+ DocumentEntity saved = manager.insert(documentEntity);
+
+ //READ
+ DocumentQuery query = select().from(DOCUMENT_COLLECTION).where(KEY_NAME).eq("100").build();
+ List entities = manager.select(query);
+ System.out.println(entities.get(0));
+
+ //UPDATE
+ saved.add(Document.of("author", "baeldung"));
+ DocumentEntity updated = manager.update(saved);
+ System.out.println(updated);
+
+ //DELETE
+ DocumentDeleteQuery deleteQuery = delete().from(DOCUMENT_COLLECTION).where(KEY_NAME).eq("100").build();
+ manager.delete(deleteQuery);
+
+ List documentEntityList = manager.select(select().from(DOCUMENT_COLLECTION).build());
+ System.out.println(documentEntityList);
+ }
+ }
+
+}
diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/MongoDbInit.java b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/MongoDbInit.java
new file mode 100644
index 0000000000..19bb347581
--- /dev/null
+++ b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/MongoDbInit.java
@@ -0,0 +1,32 @@
+package com.baeldung.jnosql.diana.document;
+
+import de.flapdoodle.embed.mongo.MongodExecutable;
+import de.flapdoodle.embed.mongo.MongodProcess;
+import de.flapdoodle.embed.mongo.MongodStarter;
+import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
+import de.flapdoodle.embed.mongo.config.Net;
+import de.flapdoodle.embed.mongo.distribution.Version;
+import de.flapdoodle.embed.process.runtime.Network;
+
+import java.io.IOException;
+
+public abstract class MongoDbInit {
+
+ private static final MongodStarter starter = MongodStarter.getDefaultInstance();
+ private static MongodExecutable _mongodExe;
+ private static MongodProcess _mongod;
+
+ public static void startMongoDb() throws IOException {
+ _mongodExe = starter.prepare(new MongodConfigBuilder()
+ .version(Version.Main.DEVELOPMENT)
+ .net(new Net("localhost", 27017, Network.localhostIsIPv6()))
+ .build());
+ _mongod = _mongodExe.start();
+ }
+
+ public static void stopMongoDb(){
+ _mongod.stop();
+ _mongodExe.stop();
+ }
+
+}
\ No newline at end of file
diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/Book.java b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/Book.java
new file mode 100644
index 0000000000..afa20e66b1
--- /dev/null
+++ b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/Book.java
@@ -0,0 +1,63 @@
+package com.baeldung.jnosql.diana.key;
+
+import java.io.Serializable;
+
+public class Book implements Serializable {
+
+ private String isbn;
+ private String name;
+ private String author;
+ private int pages;
+
+ public Book() {
+ }
+
+ public Book(String isbn, String name, String author, int pages) {
+ this.isbn = isbn;
+ this.name = name;
+ this.author = author;
+ this.pages = pages;
+ }
+
+ public String getIsbn() {
+ return isbn;
+ }
+
+ public void setIsbn(String isbn) {
+ this.isbn = isbn;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getAuthor() {
+ return author;
+ }
+
+ public void setAuthor(String author) {
+ this.author = author;
+ }
+
+ public int getPages() {
+ return pages;
+ }
+
+ public void setPages(int pages) {
+ this.pages = pages;
+ }
+
+ @Override
+ public String toString() {
+ return "Book{" +
+ "isbn='" + isbn + '\'' +
+ ", name='" + name + '\'' +
+ ", author='" + author + '\'' +
+ ", pages=" + pages +
+ '}';
+ }
+}
diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/KeyValueApp.java b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/KeyValueApp.java
new file mode 100644
index 0000000000..ab51bfa4fc
--- /dev/null
+++ b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/KeyValueApp.java
@@ -0,0 +1,33 @@
+package com.baeldung.jnosql.diana.key;
+
+import com.hazelcast.core.Hazelcast;
+import org.jnosql.diana.api.Value;
+import org.jnosql.diana.api.key.BucketManager;
+import org.jnosql.diana.api.key.BucketManagerFactory;
+import org.jnosql.diana.api.key.KeyValueConfiguration;
+import org.jnosql.diana.api.key.KeyValueEntity;
+import org.jnosql.diana.hazelcast.key.HazelcastKeyValueConfiguration;
+
+import java.util.Optional;
+
+public class KeyValueApp {
+
+ private static final String BUCKET_NAME = "books";
+
+ public static void main(String... args) throws Exception {
+ KeyValueConfiguration configuration = new HazelcastKeyValueConfiguration();
+ try (BucketManagerFactory managerFactory = configuration.get()) {
+ BucketManager manager = managerFactory.getBucketManager(BUCKET_NAME);
+
+ Book book = new Book("12345", "JNoSQL in Action", "baeldung", 420);
+ KeyValueEntity keyValueEntity = KeyValueEntity.of(book.getIsbn(), book);
+ manager.put(keyValueEntity);
+
+ Optional optionalValue = manager.get("12345");
+ Value value = optionalValue.get();
+ Book savedBook = value.get(Book.class);
+ System.out.println(savedBook);
+ }
+ Hazelcast.shutdownAll();
+ }
+}
diff --git a/jnosql/jnosql-diana/src/main/resources/diana-cassandra.properties b/jnosql/jnosql-diana/src/main/resources/diana-cassandra.properties
new file mode 100644
index 0000000000..5d7d840d65
--- /dev/null
+++ b/jnosql/jnosql-diana/src/main/resources/diana-cassandra.properties
@@ -0,0 +1,5 @@
+cassandra-host-1=localhost
+cassandra-port=9142
+#cassandra-threads-number=2
+cassandra-query-1=CREATE KEYSPACE IF NOT EXISTS myKeySpace WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};
+cassandra-query-2=CREATE COLUMNFAMILY IF NOT EXISTS myKeySpace.books (id bigint PRIMARY KEY, name text);
diff --git a/jnosql/jnosql-diana/src/main/resources/diana-hazelcast.properties b/jnosql/jnosql-diana/src/main/resources/diana-hazelcast.properties
new file mode 100644
index 0000000000..010b4a6e47
--- /dev/null
+++ b/jnosql/jnosql-diana/src/main/resources/diana-hazelcast.properties
@@ -0,0 +1 @@
+hazelcast-instanceName=hazelcast
\ No newline at end of file
diff --git a/jnosql/jnosql-diana/src/main/resources/diana-mongodb.properties b/jnosql/jnosql-diana/src/main/resources/diana-mongodb.properties
new file mode 100644
index 0000000000..5b425bd7bf
--- /dev/null
+++ b/jnosql/jnosql-diana/src/main/resources/diana-mongodb.properties
@@ -0,0 +1,2 @@
+#Define Host and Port
+mongodb-server-host-1=localhost:27017
diff --git a/jnosql/pom.xml b/jnosql/pom.xml
new file mode 100644
index 0000000000..c87ad3cf4b
--- /dev/null
+++ b/jnosql/pom.xml
@@ -0,0 +1,23 @@
+
+
+ 4.0.0
+
+ com.baeldung.jnosql
+ jnosql
+ 1.0-SNAPSHOT
+ pom
+
+
+ 1.8
+ 1.8
+ 0.0.5
+
+
+
+ jnosql-diana
+ jnosql-artemis
+
+
+
diff --git a/jooby/pom.xml b/jooby/pom.xml
index 5bd7f27d88..2867b7f4b6 100644
--- a/jooby/pom.xml
+++ b/jooby/pom.xml
@@ -44,6 +44,7 @@
org.apache.maven.plugins
maven-shade-plugin
+ ${maven-shade-plugin.version}
@@ -52,6 +53,8 @@
1.1.3
com.baeldung.jooby.App
1.1.3
+
+ 2.4.3
diff --git a/junit5/README.md b/junit5/README.md
deleted file mode 100644
index fb1685fdd5..0000000000
--- a/junit5/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-## Relevant articles:
-- [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order)
diff --git a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiLiveTest.java
similarity index 99%
rename from libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java
rename to libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiLiveTest.java
index 09d31eac21..8d60b40bb0 100644
--- a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java
+++ b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiLiveTest.java
@@ -31,7 +31,7 @@ import org.springframework.web.client.RestTemplate;
import io.specto.hoverfly.junit.core.SimulationSource;
import io.specto.hoverfly.junit.rule.HoverflyRule;
-public class HoverflyApiIntegrationTest {
+public class HoverflyApiLiveTest {
private static final SimulationSource source = dsl(service("http://www.baeldung.com").get("/api/courses/1").willReturn(success().body(jsonWithSingleQuotes("{'id':'1','name':'HCI'}")))
diff --git a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceIntegrationTest.java b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceTemporaryLiveTest.java
similarity index 96%
rename from libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceIntegrationTest.java
rename to libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceTemporaryLiveTest.java
index 75dae2b2fa..46cc77cbba 100644
--- a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceIntegrationTest.java
+++ b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceTemporaryLiveTest.java
@@ -5,7 +5,7 @@ import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.assertThat;
-public class HelloWorldServiceIntegrationTest extends AbstractIntegrationTest {
+public class HelloWorldServiceTemporaryLiveTest extends AbstractIntegrationTest {
@Test
public void whenGetIsCalledTwoTimes_thenTheSecondShouldHitTheCache() {
diff --git a/libraries/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java b/libraries/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java
index d2ad65d840..96ed090482 100644
--- a/libraries/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java
+++ b/libraries/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java
@@ -17,7 +17,7 @@ public class JMapperIntegrationTest {
@Test
- public void giventUser_whenUseAnnotation_thenConverted(){
+ public void givenUser_whenUseAnnotation_thenConverted(){
JMapper userMapper = new JMapper<>(UserDto.class, User.class);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
@@ -29,7 +29,7 @@ public class JMapperIntegrationTest {
}
@Test
- public void giventUser_whenUseGlobalMapAnnotation_thenConverted(){
+ public void givenUser_whenUseGlobalMapAnnotation_thenConverted(){
JMapper userMapper= new JMapper<>(UserDto1.class, User.class);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
@@ -41,7 +41,7 @@ public class JMapperIntegrationTest {
}
@Test
- public void giventUser_whenUseAnnotationExplicitConversion_thenConverted(){
+ public void givenUser_whenUseAnnotationExplicitConversion_thenConverted(){
JMapper userMapper = new JMapper<>(UserDto.class, User.class);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
@@ -56,7 +56,7 @@ public class JMapperIntegrationTest {
//======================= XML
@Test
- public void giventUser_whenUseXml_thenConverted(){
+ public void givenUser_whenUseXml_thenConverted(){
JMapper userMapper = new JMapper<>(UserDto.class, User.class,"user_jmapper.xml");
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
@@ -68,7 +68,7 @@ public class JMapperIntegrationTest {
}
@Test
- public void giventUser_whenUseXmlGlobal_thenConverted(){
+ public void givenUser_whenUseXmlGlobal_thenConverted(){
JMapper userMapper = new JMapper<>(UserDto1.class, User.class,"user_jmapper1.xml");
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
@@ -82,7 +82,7 @@ public class JMapperIntegrationTest {
// ===== API
@Test
- public void giventUser_whenUseApi_thenConverted(){
+ public void givenUser_whenUseApi_thenConverted(){
JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class)
.add(attribute("id").value("id"))
.add(attribute("username").value("email"))
@@ -98,7 +98,7 @@ public class JMapperIntegrationTest {
}
@Test
- public void giventUser_whenUseApiGlobal_thenConverted(){
+ public void givenUser_whenUseApiGlobal_thenConverted(){
JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class)
.add(global())
) ;
diff --git a/libraries/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java b/libraries/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java
index 054332a704..6af2865159 100644
--- a/libraries/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java
+++ b/libraries/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java
@@ -16,7 +16,7 @@ public class JMapperRelationalIntegrationTest {
@Test
- public void giventUser_whenUseAnnotation_thenConverted(){
+ public void givenUser_whenUseAnnotation_thenConverted(){
RelationalJMapper relationalMapper = new RelationalJMapper<>(User.class);
User user = new User(1L,"john@test.com");
@@ -34,7 +34,7 @@ public class JMapperRelationalIntegrationTest {
//======================= XML
@Test
- public void giventUser_whenUseXml_thenConverted(){
+ public void givenUser_whenUseXml_thenConverted(){
RelationalJMapper relationalMapper = new RelationalJMapper<>(User.class,"user_jmapper2.xml");
User user = new User(1L,"john@test.com");
@@ -53,7 +53,7 @@ public class JMapperRelationalIntegrationTest {
// ===== API
@Test
- public void giventUser_whenUseApi_thenConverted(){
+ public void givenUser_whenUseApi_thenConverted(){
JMapperAPI jmapperApi = new JMapperAPI()
.add(mappedClass(User.class)
.add(attribute("id").value("id").targetClasses(UserDto1.class,UserDto2.class))
diff --git a/maven/pom.xml b/maven/pom.xml
index b3f15ba90d..a409432f8b 100644
--- a/maven/pom.xml
+++ b/maven/pom.xml
@@ -48,8 +48,10 @@
DataTest.java
+ TestFail.java
DataCheck.java
+ true
diff --git a/maven/src/test/java/testfail/TestFail.java b/maven/src/test/java/testfail/TestFail.java
new file mode 100644
index 0000000000..16f1619db4
--- /dev/null
+++ b/maven/src/test/java/testfail/TestFail.java
@@ -0,0 +1,15 @@
+package testfail;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertNotNull;
+
+public class TestFail {
+ @Test
+ public void whenMessageAssigned_thenItIsNotNull() {
+ String message = "hello there";
+ message = null;
+ assertNotNull(message);
+ }
+
+}
diff --git a/micronaut/hello-world/.mvn/jvm.config b/micronaut/.mvn/jvm.config
similarity index 100%
rename from micronaut/hello-world/.mvn/jvm.config
rename to micronaut/.mvn/jvm.config
diff --git a/micronaut/hello-world/.mvn/wrapper/MavenWrapperDownloader.java b/micronaut/.mvn/wrapper/MavenWrapperDownloader.java
similarity index 99%
rename from micronaut/hello-world/.mvn/wrapper/MavenWrapperDownloader.java
rename to micronaut/.mvn/wrapper/MavenWrapperDownloader.java
index d475a89ce1..66a3132a52 100644
--- a/micronaut/hello-world/.mvn/wrapper/MavenWrapperDownloader.java
+++ b/micronaut/.mvn/wrapper/MavenWrapperDownloader.java
@@ -106,5 +106,4 @@ public class MavenWrapperDownloader {
fos.close();
rbc.close();
}
-
}
diff --git a/micronaut/hello-world/.mvn/wrapper/maven-wrapper.jar b/micronaut/.mvn/wrapper/maven-wrapper.jar
similarity index 100%
rename from micronaut/hello-world/.mvn/wrapper/maven-wrapper.jar
rename to micronaut/.mvn/wrapper/maven-wrapper.jar
diff --git a/micronaut/hello-world/.mvn/wrapper/maven-wrapper.properties b/micronaut/.mvn/wrapper/maven-wrapper.properties
similarity index 100%
rename from micronaut/hello-world/.mvn/wrapper/maven-wrapper.properties
rename to micronaut/.mvn/wrapper/maven-wrapper.properties
diff --git a/micronaut/hello-world/Dockerfile b/micronaut/Dockerfile
similarity index 100%
rename from micronaut/hello-world/Dockerfile
rename to micronaut/Dockerfile
diff --git a/micronaut/hello-world/micronaut-cli.yml b/micronaut/micronaut-cli.yml
similarity index 100%
rename from micronaut/hello-world/micronaut-cli.yml
rename to micronaut/micronaut-cli.yml
diff --git a/micronaut/hello-world/mvnw b/micronaut/mvnw
similarity index 100%
rename from micronaut/hello-world/mvnw
rename to micronaut/mvnw
diff --git a/micronaut/hello-world/mvnw.cmd b/micronaut/mvnw.cmd
similarity index 100%
rename from micronaut/hello-world/mvnw.cmd
rename to micronaut/mvnw.cmd
diff --git a/micronaut/hello-world/pom.xml b/micronaut/pom.xml
similarity index 100%
rename from micronaut/hello-world/pom.xml
rename to micronaut/pom.xml
diff --git a/micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java
similarity index 100%
rename from micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java
rename to micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java
diff --git a/micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java
similarity index 100%
rename from micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java
rename to micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java
diff --git a/micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/server/ServerApplication.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/ServerApplication.java
similarity index 100%
rename from micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/server/ServerApplication.java
rename to micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/ServerApplication.java
diff --git a/micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/server/controller/AsyncGreetController.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/controller/AsyncGreetController.java
similarity index 100%
rename from micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/server/controller/AsyncGreetController.java
rename to micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/controller/AsyncGreetController.java
diff --git a/micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/server/controller/GreetController.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/controller/GreetController.java
similarity index 100%
rename from micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/server/controller/GreetController.java
rename to micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/controller/GreetController.java
diff --git a/micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/server/service/EnglishGreetingService.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/EnglishGreetingService.java
similarity index 100%
rename from micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/server/service/EnglishGreetingService.java
rename to micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/EnglishGreetingService.java
diff --git a/micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/server/service/GreetingService.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/GreetingService.java
similarity index 100%
rename from micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/server/service/GreetingService.java
rename to micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/GreetingService.java
diff --git a/micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/server/service/SpanishGreetingService.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/SpanishGreetingService.java
similarity index 100%
rename from micronaut/hello-world/src/main/java/com/baeldung/micronaut/helloworld/server/service/SpanishGreetingService.java
rename to micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/SpanishGreetingService.java
diff --git a/micronaut/hello-world/src/main/resources/application.yml b/micronaut/src/main/resources/application.yml
similarity index 100%
rename from micronaut/hello-world/src/main/resources/application.yml
rename to micronaut/src/main/resources/application.yml
diff --git a/micronaut/hello-world/src/main/resources/logback.xml b/micronaut/src/main/resources/logback.xml
similarity index 100%
rename from micronaut/hello-world/src/main/resources/logback.xml
rename to micronaut/src/main/resources/logback.xml
diff --git a/micronaut/hello-world/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java
similarity index 100%
rename from micronaut/hello-world/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java
rename to micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java
diff --git a/micronaut/hello-world/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java
similarity index 100%
rename from micronaut/hello-world/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java
rename to micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java
diff --git a/msf4j/pom.xml b/msf4j/pom.xml
index f2cfe10f57..cca8281764 100644
--- a/msf4j/pom.xml
+++ b/msf4j/pom.xml
@@ -1,33 +1,33 @@
-
- 4.0.0
- com.baeldung.msf4j
- msf4j
- 0.0.1-SNAPSHOT
- WSO2 MSF4J Microservice
+
+ 4.0.0
+ com.baeldung.msf4j
+ msf4j
+ 0.0.1-SNAPSHOT
-
- org.wso2.msf4j
- msf4j-service
- 2.6.0
-
+
+ org.wso2.msf4j
+ msf4j-service
+ 2.6.0
+
-
-
- org.wso2.msf4j
- msf4j-spring
- ${msf4j.version}
-
-
- org.wso2.msf4j
- msf4j-mustache-template
- ${msf4j.version}
-
-
+
+
+ org.wso2.msf4j
+ msf4j-spring
+ ${msf4j.version}
+
+
+ org.wso2.msf4j
+ msf4j-mustache-template
+ ${msf4j.version}
+
+
-
- com.baeldung.msf4j.msf4jintro.Application
- 2.6.1
-
+
+ com.baeldung.msf4j.msf4jintro.Application
+ 2.6.1
+
\ No newline at end of file
diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml
index 2d45120f32..ab6162a5a5 100644
--- a/parent-boot-2/pom.xml
+++ b/parent-boot-2/pom.xml
@@ -5,8 +5,7 @@
parent-boot-2
0.0.1-SNAPSHOT
pom
- Parent Boot 2
- Parent for all spring boot 2 modules
+ Parent for all Spring Boot 2 modules
org.springframework.boot
diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml
index 372cb2b4c3..36ec6b5ac8 100644
--- a/persistence-modules/java-cassandra/pom.xml
+++ b/persistence-modules/java-cassandra/pom.xml
@@ -2,9 +2,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.baeldung
- cassandra-java-client
+ java-cassandra
1.0.0-SNAPSHOT
- cassandra-java-client
com.baeldung
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
index f1ad30b090..8157945e2c 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
@@ -3,13 +3,15 @@ package com.baeldung.hibernate.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
+
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
import javax.persistence.Id;
-import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@@ -18,7 +20,7 @@ import javax.persistence.Table;
public class Employee implements Serializable {
@Id
@Column(name = "employee_id")
- @GeneratedValue
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long employeeId;
@Column(name = "first_name")
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/HibernateSearchConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/HibernateSearchConfig.java
index 6bbd2625fc..d6445c3cb0 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/HibernateSearchConfig.java
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/HibernateSearchConfig.java
@@ -50,6 +50,8 @@ public class HibernateSearchConfig {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
+ dataSource.setUsername(env.getProperty("jdbc.user"));
+ dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
index 5dace1f742..44cbfadb25 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
@@ -19,7 +19,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
-@PropertySource({ "classpath:persistence-mysql.properties" })
+@PropertySource({ "classpath:persistence-h2.properties" })
@ComponentScan({ "com.baeldung.hibernate.manytomany" })
public class PersistenceConfig {
@@ -61,7 +61,7 @@ public class PersistenceConfig {
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
- //hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
+ hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", "true");
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java
index e64f0a4efe..74ac0a269e 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java
@@ -21,7 +21,7 @@ import java.util.Properties;
@Configuration
@EnableTransactionManagement
-@PropertySource({ "classpath:persistence-mysql.properties" })
+@PropertySource({ "classpath:persistence-h2.properties" })
@ComponentScan({ "com.baeldung.persistence" })
public class PersistenceConfig {
diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties
index 0325174b67..5a137e2310 100644
--- a/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties
+++ b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties
@@ -3,7 +3,7 @@ jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.eventGeneratedId=sa
jdbc.user=sa
-jdbc.pass=sa
+jdbc.pass=
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml b/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml
new file mode 100644
index 0000000000..a7a23ec70d
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml
@@ -0,0 +1,16 @@
+
+
+
+
+ org.h2.Driver
+
+ jdbc:h2:mem:spring_hibernate_many_to_many
+ sa
+ org.hibernate.dialect.H2Dialect
+ thread
+ true
+ create-drop
+
+
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java
index 010eb5b8a1..78c4116c67 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java
+++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java
@@ -24,7 +24,7 @@ import com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
-@PropertySource({ "classpath:persistence-mysql.properties" })
+@PropertySource({ "classpath:persistence-h2.properties" })
@ComponentScan({ "org.baeldung.persistence" })
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
public class PersistenceJPAConfig {
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java
index 97b5803d73..079888155e 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java
+++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java
@@ -11,7 +11,7 @@ import javax.persistence.Table;
public class Possession {
@Id
- @GeneratedValue(strategy = GenerationType.AUTO)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java
index 1c6399dc44..61904198f5 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java
+++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java
@@ -15,7 +15,7 @@ import javax.persistence.Table;
public class User {
@Id
- @GeneratedValue(strategy = GenerationType.AUTO)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties
index 2c3e18b58d..716a96fde3 100644
--- a/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties
+++ b/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties
@@ -2,7 +2,7 @@
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.user=sa
-# jdbc.pass=
+jdbc.pass=
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties
index 539535528c..ce1b6da9ff 100644
--- a/persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties
+++ b/persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties
@@ -1,12 +1,12 @@
# jdbc.X
-jdbc.driverClassName=com.mysql.cj.jdbc.Driver
-user.jdbc.url=jdbc:mysql://localhost:3306/spring_jpa_user?createDatabaseIfNotExist=true
-product.jdbc.url=jdbc:mysql://localhost:3306/spring_jpa_product?createDatabaseIfNotExist=true
-jdbc.user=tutorialuser
-jdbc.pass=tutorialmy5ql
+jdbc.driverClassName=org.h2.Driver
+user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS SPRING_JPA_USER
+product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS SPRING_JPA_PRODUCT
+jdbc.user=sa
+jdbc.pass=
# hibernate.X
-hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
+hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=false
diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties
index e1d6bfa45a..405e6ff109 100644
--- a/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties
+++ b/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties
@@ -2,7 +2,7 @@
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.user=sa
-# jdbc.pass=
+jdbc.pass=
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence.xml b/persistence-modules/spring-jpa/src/main/resources/persistence.xml
index 5afc0af94d..65bad29cdc 100644
--- a/persistence-modules/spring-jpa/src/main/resources/persistence.xml
+++ b/persistence-modules/spring-jpa/src/main/resources/persistence.xml
@@ -7,7 +7,7 @@
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
-
+
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java
index f81247e3cd..47355471b9 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java
@@ -9,11 +9,13 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = DataSourceRoutingTestConfiguration.class)
+@DirtiesContext
public class DataSourceRoutingIntegrationTest {
@Autowired
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java
index 09d118fedc..e5fb728a0a 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java
@@ -10,6 +10,6 @@ public class PersistenceJPAConfigDeletion extends PersistenceJPAConfigL2Cache {
@Override
protected String[] getPackagesToScan() {
- return new String[] { "org.baeldung.persistence.deletion.model" };
+ return new String[] { "org.baeldung.persistence.deletion.model", "org.baeldung.persistence.model" };
}
}
\ No newline at end of file
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java
index 9432420878..9a90b857e5 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java
@@ -11,6 +11,7 @@ import org.baeldung.inmemory.persistence.model.SkillTag;
import org.baeldung.inmemory.persistence.model.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@@ -26,6 +27,7 @@ import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class)
@Transactional
+@DirtiesContext
public class AdvancedTaggingIntegrationTest {
@Resource
private StudentRepository studentRepository;
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java
index 7c6ec9b6da..f3cf921632 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java
@@ -12,11 +12,13 @@ import org.baeldung.inmemory.persistence.model.Student;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { StudentJPAH2Config.class })
+@DirtiesContext
public class ExtendedStudentRepositoryIntegrationTest {
@Resource
private ExtendedStudentRepository extendedStudentRepository;
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java
index 3d9e376e81..9ddc48460a 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java
@@ -5,6 +5,7 @@ import org.baeldung.inmemory.persistence.dao.StudentRepository;
import org.baeldung.inmemory.persistence.model.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@@ -20,6 +21,7 @@ import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class)
@Transactional
+@DirtiesContext
public class InMemoryDBIntegrationTest {
@Resource
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java
index 90db9f4e74..9effd4717f 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java
@@ -11,6 +11,7 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.data.mapping.PropertyReferenceException;
+import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
@@ -25,6 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = PersistenceJPAConfigL2Cache.class)
+@DirtiesContext
public class UserRepositoryIntegrationTest {
private final String USER_NAME_ADAM = "Adam";
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java
index f42a4e9be1..0dbb7dbfe8 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java
@@ -8,6 +8,7 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@@ -23,6 +24,7 @@ import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfigDeletion.class }, loader = AnnotationConfigContextLoader.class)
+@DirtiesContext
public class DeletionIntegrationTest {
@PersistenceContext
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java
index 091bec0ba0..bf49a431e1 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java
@@ -16,17 +16,20 @@ import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.baeldung.config.PersistenceJPAConfig;
+import org.baeldung.config.PersistenceJPAConfigL2Cache;
import org.baeldung.persistence.model.Foo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class)
+@DirtiesContext
public class FooPaginationPersistenceIntegrationTest {
@PersistenceContext
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java
index 4c57865f74..45316cf06c 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java
@@ -3,6 +3,7 @@ package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.baeldung.config.PersistenceJPAConfig;
+import org.baeldung.config.PersistenceJPAConfigL2Cache;
import org.baeldung.persistence.model.Foo;
import org.junit.Assert;
import org.junit.Test;
@@ -11,12 +12,14 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
+import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class)
+@DirtiesContext
public class FooServicePersistenceIntegrationTest {
@Autowired
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java
index 3c9f509da5..61a3bfd565 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java
@@ -10,17 +10,19 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
-import org.baeldung.config.PersistenceJPAConfig;
+import org.baeldung.config.PersistenceJPAConfigL2Cache;
import org.baeldung.persistence.model.Bar;
import org.baeldung.persistence.model.Foo;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class)
+@DirtiesContext
@SuppressWarnings("unchecked")
public class FooServiceSortingIntegrationTest {
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java
index 040eee1c73..50fdf5f0f3 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java
@@ -10,16 +10,19 @@ import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.baeldung.config.PersistenceJPAConfig;
+import org.baeldung.config.PersistenceJPAConfigL2Cache;
import org.baeldung.persistence.model.Foo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class)
+@DirtiesContext
public class FooServiceSortingWitNullsManualIntegrationTest {
@PersistenceContext
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java
index f20af34057..6cd187230c 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java
@@ -18,6 +18,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@@ -26,6 +27,7 @@ import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { UserConfig.class, ProductConfig.class })
@EnableTransactionManagement
+@DirtiesContext
public class JpaMultipleDBIntegrationTest {
@Autowired
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java
index 907043b8ce..4de8d321d5 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java
@@ -8,6 +8,7 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@@ -24,6 +25,7 @@ import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class)
+@DirtiesContext
public class SecondLevelCacheIntegrationTest {
@PersistenceContext
diff --git a/pom.xml b/pom.xml
index 5ed7f7c33f..3e0d37e19f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,471 +1,1108 @@
-
- 4.0.0
+
+ 4.0.0
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
- parent-modules
- pom
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+ parent-modules
+ pom
-
- parent-boot-1
- parent-boot-2
- parent-spring-4
- parent-spring-5
- parent-java
- asm
- atomix
- apache-cayenne
- aws
- aws-lambda
- akka-streams
- algorithms
- annotations
- apache-cxf
- apache-fop
- apache-poi
- apache-tika
- apache-thrift
- apache-curator
- apache-zookeeper
- apache-opennlp
- autovalue
- axon
- azure
- bootique
- cdi
-
- core-java
- core-java-collections
- core-java-io
- core-java-8
- core-kotlin
- core-groovy
- core-java-concurrency
- couchbase
- deltaspike
- dozer
- ethereum
- ejb
- feign
- flips
- testing-modules/gatling
- geotools
- testing-modules/groovy-spock
- google-cloud
- google-web-toolkit
- gson
- guava
- guava-modules/guava-18
- guava-modules/guava-19
- guava-modules/guava-21
- guice
- disruptor
- spring-static-resources
- hazelcast
- hbase
- hibernate5
- httpclient
- hystrix
- image-processing
- immutables
- influxdb
- jackson
- persistence-modules/java-cassandra
- vavr
- java-lite
- java-numbers
- java-rmi
- java-vavr-stream
- javax-servlets
- javaxval
- jaxb
- javafx
- jgroups
- jee-7
- jhipster/jhipster-monolithic
- jjwt
- jpa-storedprocedure
- jsf
- json-path
- json
- jsoup
- testing-modules/junit-5
- jws
- libraries
- libraries-data
- linkrest
- logging-modules/log-mdc
- logging-modules/log4j
- logging-modules/log4j2
- logging-modules/logback
- lombok
- mapstruct
- metrics
- maven
- mesos-marathon
- msf4j
- testing-modules/mockito
- testing-modules/mockito-2
- testing-modules/mocks
- mustache
- mvn-wrapper
- noexception
- orientdb
- osgi
- orika
- patterns
- pdf
- protobuffer
- persistence-modules/querydsl
- reactor-core
- persistence-modules/redis
- testing-modules/rest-assured
- testing-modules/rest-testing
- resteasy
- rxjava
- spring-swagger-codegen
- testing-modules/selenium-junit-testng
- persistence-modules/solr
- spark-java
- spring-4
- spring-5
- spring-5-reactive
- spring-5-mvc
- spring-5-security
- spring-activiti
- spring-akka
- spring-amqp
- spring-all
- spring-amqp-simple
- spring-apache-camel
- spring-batch
- spring-bom
- spring-boot
- spring-boot-keycloak
- spring-boot-bootstrap
- spring-boot-admin
- spring-boot-ops
- spring-boot-persistence
- spring-boot-security
- spring-boot-mvc
- spring-boot-logging-log4j2
- spring-cloud-data-flow
- spring-cloud
- spring-core
- spring-cucumber
- spring-ejb
- spring-aop
- persistence-modules/spring-data-cassandra
- spring-data-couchbase-2
- persistence-modules/spring-data-dynamodb
- spring-data-elasticsearch
- spring-data-keyvalue
- spring-data-mongodb
- persistence-modules/spring-data-neo4j
- persistence-modules/spring-data-redis
- spring-data-rest
- persistence-modules/spring-data-solr
- spring-dispatcher-servlet
- spring-exceptions
- spring-freemarker
- persistence-modules/spring-hibernate-3
- spring-hibernate4
- persistence-modules/spring-hibernate-5
- persistence-modules/spring-data-eclipselink
- spring-integration
- spring-jenkins-pipeline
- spring-jersey
- jmeter
- spring-jms
- spring-jooq
- persistence-modules/spring-jpa
- spring-kafka
- spring-katharsis
- spring-ldap
- spring-mockito
- spring-mvc-forms-jsp
- spring-mvc-forms-thymeleaf
- spring-mvc-java
- spring-mvc-velocity
- spring-mvc-webflow
- spring-mvc-xml
- spring-mvc-kotlin
- spring-protobuf
- spring-quartz
- spring-rest-angular
- spring-rest-full
- spring-rest-query-language
- spring-rest
- spring-rest-simple
- spring-security-acl
- spring-security-cache-control
- spring-security-client/spring-security-jsp-authentication
- spring-security-client/spring-security-jsp-authorize
- spring-security-client/spring-security-jsp-config
- spring-security-client/spring-security-mvc
- spring-security-client/spring-security-thymeleaf-authentication
- spring-security-client/spring-security-thymeleaf-authorize
- spring-security-client/spring-security-thymeleaf-config
- spring-security-core
- spring-security-mvc-boot
- spring-security-mvc-custom
- spring-security-mvc-digest-auth
- spring-security-mvc-ldap
- spring-security-mvc-login
- spring-security-mvc-persisted-remember-me
- spring-security-mvc-session
- spring-security-mvc-socket
- spring-security-openid
-
- spring-security-rest-basic-auth
- spring-security-rest-custom
- spring-security-rest
- spring-security-sso
- spring-security-x509
- spring-session
- spring-sleuth
- spring-social-login
- spring-spel
- spring-state-machine
- spring-thymeleaf
- spring-userservice
- spring-zuul
- spring-reactor
- spring-vertx
- spring-jinq
- spring-rest-embedded-tomcat
- testing-modules/testing
- testing-modules/testng
- video-tutorials
- xml
- xmlunit-2
- struts-2
- apache-velocity
- apache-solrj
- rabbitmq
- vertx
- persistence-modules/spring-data-gemfire
- mybatis
- spring-drools
- drools
- persistence-modules/liquibase
- spring-boot-property-exp
- testing-modules/mockserver
- testing-modules/test-containers
- undertow
- vertx-and-rxjava
- saas
- deeplearning4j
- lucene
- vraptor
- persistence-modules/java-cockroachdb
- spring-security-thymeleaf
- persistence-modules/java-jdbi
- jersey
- java-spi
- performance-tests
- twilio
- spring-boot-ctx-fluent
- java-ee-8-security-api
- spring-webflux-amqp
- antlr
- maven-archetype
- apache-meecrowave
-
+
+
+
+ org.slf4j
+ slf4j-api
+ ${org.slf4j.version}
+
+
+ ch.qos.logback
+ logback-classic
+ ${logback.version}
+
+
+ ch.qos.logback
+ logback-core
+ ${logback.version}
+
+
+ org.slf4j
+ jcl-over-slf4j
+ ${org.slf4j.version}
+
-
-
-
- org.slf4j
- slf4j-api
- ${org.slf4j.version}
-
-
- ch.qos.logback
- logback-classic
- ${logback.version}
-
-
- ch.qos.logback
- logback-core
- ${logback.version}
-
-
- org.slf4j
- jcl-over-slf4j
- ${org.slf4j.version}
-
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ ${junit.jupiter.version}
+ test
+
+
+ org.hamcrest
+ hamcrest-core
+ ${org.hamcrest.version}
+ test
+
+
+ org.hamcrest
+ hamcrest-library
+ ${org.hamcrest.version}
+ test
+
+
+ org.hamcrest
+ hamcrest-all
+ ${org.hamcrest.version}
+ test
+
+
+ org.mockito
+ mockito-core
+ ${mockito.version}
+ test
+
+
-
-
- junit
- junit
- ${junit.version}
- test
-
-
- org.junit.jupiter
- junit-jupiter-engine
- ${junit.jupiter.version}
- test
-
-
- org.hamcrest
- hamcrest-core
- ${org.hamcrest.version}
- test
-
-
- org.hamcrest
- hamcrest-library
- ${org.hamcrest.version}
- test
-
-
- org.hamcrest
- hamcrest-all
- ${org.hamcrest.version}
- test
-
-
- org.mockito
- mockito-core
- ${mockito.version}
- test
-
-
-
-
-
-
- org.codehaus.mojo
- exec-maven-plugin
- ${exec-maven-plugin.version}
-
- maven
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
- 3
- true
-
- **/*IntegrationTest.java
- **/*IntTest.java
- **/*LongRunningUnitTest.java
- **/*ManualTest.java
- **/JdbcTest.java
- **/*LiveTest.java
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- ${java.version}
- ${java.version}
-
-
-
- org.apache.maven.plugins
- maven-pmd-plugin
- ${maven-pmd-plugin.version}
-
-
- org.baeldung.pmd
- custom-pmd
- ${custom-pmd.version}
-
-
-
- 5
- false
- true
- true
- true
- true
- UTF-8
- ${java.version}
-
- ${tutorialsproject.basedir}/baeldung-pmd-rules.xml
-
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ ${exec-maven-plugin.version}
+
+ maven
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+ 3
+ true
+
+ **/*IntegrationTest.java
+ **/*IntTest.java
+ **/*LongRunningUnitTest.java
+ **/*ManualTest.java
+ **/JdbcTest.java
+ **/*LiveTest.java
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${java.version}
+ ${java.version}
+
+
+
+ org.apache.maven.plugins
+ maven-pmd-plugin
+ ${maven-pmd-plugin.version}
+
+
+ org.baeldung.pmd
+ custom-pmd
+ ${custom-pmd.version}
+
+
+
+ 5
+ false
+ true
+ true
+ true
+ true
+ UTF-8
+ ${java.version}
+
+ ${tutorialsproject.basedir}/baeldung-pmd-rules.xml
+
target/generated-sources
-
-
-
- compile
-
- check
-
-
-
-
-
- org.commonjava.maven.plugins
- directory-maven-plugin
- ${directory-maven-plugin.version}
-
-
- directories
-
- directory-of
-
- validate
-
- tutorialsproject.basedir
-
- com.baeldung
- parent-modules
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-install-plugin
- ${maven-install-plugin.version}
-
- org.baeldung.pmd
- custom-pmd
- ${custom-pmd.version}
- jar
- ${tutorialsproject.basedir}/custom-pmd-${custom-pmd.version}.jar
- true
-
-
-
- install-jar-lib
-
- install-file
-
- validate
-
-
-
-
-
-
- com.vackosar.gitflowincrementalbuilder
- gitflow-incremental-builder
- ${gitflow-incremental-builder.version}
-
-
-
+
+
+
+ compile
+
+ check
+
+
+
+
+
+ org.commonjava.maven.plugins
+ directory-maven-plugin
+ ${directory-maven-plugin.version}
+
+
+ directories
+
+ directory-of
+
+ validate
+
+ tutorialsproject.basedir
+
+ com.baeldung
+ parent-modules
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-install-plugin
+ ${maven-install-plugin.version}
+
+ org.baeldung.pmd
+ custom-pmd
+ ${custom-pmd.version}
+ jar
+ ${tutorialsproject.basedir}/custom-pmd-${custom-pmd.version}.jar
+ true
+
+
+
+ install-jar-lib
+
+ install-file
+
+ validate
+
+
+
+
+
+
+ com.vackosar.gitflowincrementalbuilder
+ gitflow-incremental-builder
+ ${gitflow-incremental-builder.version}
+
+
+
+
+
+
+ org.eclipse.m2e
+ lifecycle-mapping
+ 1.0.0
+
+
+
+
+
+
+ org.commonjava.maven.plugins
+
+
+ directory-maven-plugin
+
+
+ [0.3.1,)
+
+
+ directory-of
+
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+
+
+ maven-install-plugin
+
+
+ [2.5.1,)
+
+
+ install-file
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ default
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+ 3
+ true
+
+ **/*IntegrationTest.java
+ **/*IntTest.java
+ **/*LongRunningUnitTest.java
+ **/*ManualTest.java
+ **/JdbcTest.java
+ **/*LiveTest.java
+
+
+
+
+
+
+
+
+ parent-boot-1
+ parent-boot-2
+ parent-spring-4
+ parent-spring-5
+ parent-java
+ asm
+ atomix
+ apache-cayenne
+ aws
+ aws-lambda
+ akka-streams
+ algorithms
+ annotations
+ apache-cxf
+ apache-fop
+ apache-poi
+ apache-tika
+ apache-thrift
+ apache-curator
+ apache-zookeeper
+ apache-opennlp
+ autovalue
+ axon
+ azure
+ bootique
+ cdi
+
+ core-java
+ core-java-collections
+ core-java-io
+ core-java-8
+ core-kotlin
+ core-groovy
+ core-java-concurrency
+ couchbase
+ deltaspike
+ dozer
+ ethereum
+ ejb
+ feign
+ flips
+ testing-modules/gatling
+ geotools
+ testing-modules/groovy-spock
+ google-cloud
+ google-web-toolkit
+ gson
+ guava
+ guava-modules/guava-18
+ guava-modules/guava-19
+ guava-modules/guava-21
+ guice
+ disruptor
+ spring-static-resources
+ hazelcast
+ hbase
+ hibernate5
+ httpclient
+ hystrix
+ image-processing
+ immutables
+ influxdb
+ jackson
+ persistence-modules/java-cassandra
+ vavr
+ java-lite
+ java-numbers
+ java-rmi
+ java-vavr-stream
+ javax-servlets
+ javaxval
+ jaxb
+ javafx
+ jgroups
+ jee-7
+ jhipster/jhipster-monolithic
+ jjwt
+ jpa-storedprocedure
+ jsf
+ json-path
+ json
+ jsoup
+ testing-modules/junit-5
+ jws
+ libraries
+ libraries-data
+ linkrest
+ logging-modules/log-mdc
+ logging-modules/log4j
+ logging-modules/log4j2
+ logging-modules/logback
+ lombok
+ mapstruct
+ metrics
+ maven
+ mesos-marathon
+ msf4j
+ testing-modules/mockito
+ testing-modules/mockito-2
+ testing-modules/mocks
+ mustache
+ mvn-wrapper
+ noexception
+ orientdb
+ osgi
+ orika
+ patterns
+ pdf
+ protobuffer
+ persistence-modules/querydsl
+ reactor-core
+ persistence-modules/redis
+ testing-modules/rest-assured
+ testing-modules/rest-testing
+ resteasy
+ rxjava
+ spring-swagger-codegen
+ testing-modules/selenium-junit-testng
+ persistence-modules/solr
+ spark-java
+ spring-4
+ spring-5
+ spring-5-reactive
+ spring-5-mvc
+ spring-5-security
+ spring-activiti
+ spring-akka
+ spring-amqp
+ spring-all
+ spring-amqp-simple
+ spring-apache-camel
+ spring-batch
+ spring-bom
+ spring-boot
+ spring-boot-keycloak
+ spring-boot-bootstrap
+ spring-boot-admin
+ spring-boot-ops
+ spring-boot-persistence
+ spring-boot-security
+ spring-boot-mvc
+ spring-boot-logging-log4j2
+ spring-cloud-data-flow
+ spring-cloud
+ spring-core
+ spring-cucumber
+ spring-ejb
+ spring-aop
+ persistence-modules/spring-data-cassandra
+ spring-data-couchbase-2
+ persistence-modules/spring-data-dynamodb
+ spring-data-elasticsearch
+ spring-data-keyvalue
+ spring-data-mongodb
+ persistence-modules/spring-data-neo4j
+ persistence-modules/spring-data-redis
+ spring-data-rest
+ persistence-modules/spring-data-solr
+ spring-dispatcher-servlet
+ spring-exceptions
+ spring-freemarker
+ persistence-modules/spring-hibernate-3
+ spring-hibernate4
+ persistence-modules/spring-hibernate-5
+ persistence-modules/spring-data-eclipselink
+ spring-integration
+ spring-jenkins-pipeline
+ spring-jersey
+ jmeter
+ spring-jms
+ spring-jooq
+ persistence-modules/spring-jpa
+ spring-kafka
+ spring-katharsis
+ spring-ldap
+ spring-mockito
+ spring-mvc-forms-jsp
+ spring-mvc-forms-thymeleaf
+ spring-mvc-java
+ spring-mvc-velocity
+ spring-mvc-webflow
+ spring-mvc-xml
+ spring-mvc-kotlin
+ spring-protobuf
+ spring-quartz
+ spring-rest-angular
+ spring-rest-full
+ spring-rest-query-language
+ spring-rest
+ spring-rest-simple
+ spring-security-acl
+ spring-security-cache-control
+ spring-security-client/spring-security-jsp-authentication
+ spring-security-client/spring-security-jsp-authorize
+ spring-security-client/spring-security-jsp-config
+ spring-security-client/spring-security-mvc
+ spring-security-client/spring-security-thymeleaf-authentication
+ spring-security-client/spring-security-thymeleaf-authorize
+ spring-security-client/spring-security-thymeleaf-config
+ spring-security-core
+ spring-security-mvc-boot
+ spring-security-mvc-custom
+ spring-security-mvc-digest-auth
+ spring-security-mvc-ldap
+ spring-security-mvc-login
+ spring-security-mvc-persisted-remember-me
+ spring-security-mvc-session
+ spring-security-mvc-socket
+ spring-security-openid
+
+ spring-security-rest-basic-auth
+ spring-security-rest-custom
+ spring-security-rest
+ spring-security-sso
+ spring-security-x509
+ spring-session
+ spring-sleuth
+ spring-social-login
+ spring-spel
+ spring-state-machine
+ spring-thymeleaf
+ spring-userservice
+ spring-zuul
+ spring-reactor
+ spring-vertx
+ spring-jinq
+ spring-rest-embedded-tomcat
+ testing-modules/testing
+ testing-modules/testng
+ video-tutorials
+ xml
+ xmlunit-2
+ struts-2
+ apache-velocity
+ apache-solrj
+ rabbitmq
+ vertx
+ persistence-modules/spring-data-gemfire
+ mybatis
+ spring-drools
+ drools
+ persistence-modules/liquibase
+ spring-boot-property-exp
+ testing-modules/mockserver
+ testing-modules/test-containers
+ undertow
+ vertx-and-rxjava
+ saas
+ deeplearning4j
+ lucene
+ vraptor
+ persistence-modules/java-cockroachdb
+ spring-security-thymeleaf
+ persistence-modules/java-jdbi
+ jersey
+ java-spi
+ performance-tests
+ twilio
+ spring-boot-ctx-fluent
+ java-ee-8-security-api
+ spring-webflux-amqp
+ antlr
+ maven-archetype
+ apache-meecrowave
+ spring-reactive-kotlin
+ jnosql
+
+
+
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*ManualTest.java
+ **/*LiveTest.java
+
+
+ **/*IntegrationTest.java
+ **/*IntTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
+
+ parent-boot-1
+ parent-boot-2
+ parent-spring-4
+ parent-spring-5
+ parent-java
+
+
+
+
+
+
+
+
+
+
+ testing-modules/mockito
+ testing-modules/mockito-2
+ testing-modules/mocks
+ mustache
+ mvn-wrapper
+ noexception
+ orientdb
+ osgi
+ orika
+ patterns
+ pdf
+ protobuffer
+ persistence-modules/querydsl
+ reactor-core
+ persistence-modules/redis
+ testing-modules/rest-assured
+ testing-modules/rest-testing
+ resteasy
+ rxjava
+ spring-swagger-codegen
+ testing-modules/selenium-junit-testng
+ persistence-modules/solr
+ spark-java
+ spring-4
+ spring-5
+ spring-5-reactive
+ spring-5-mvc
+ spring-5-security
+ spring-activiti
+ spring-akka
+ spring-amqp
+ spring-all
+ spring-amqp-simple
+ spring-apache-camel
+ spring-batch
+
+
+
+
+
+
+ spring-bom
+ spring-boot
+ spring-boot-keycloak
+ spring-boot-bootstrap
+ spring-boot-admin
+ spring-boot-ops
+ spring-boot-persistence
+ spring-boot-security
+ spring-boot-mvc
+ spring-boot-logging-log4j2
+ spring-cloud-data-flow
+ spring-cloud
+ spring-core
+ spring-cucumber
+ spring-ejb
+ spring-aop
+ persistence-modules/spring-data-cassandra
+ spring-data-couchbase-2
+ persistence-modules/spring-data-dynamodb
+ spring-data-elasticsearch
+ spring-data-keyvalue
+ spring-data-mongodb
+ persistence-modules/spring-data-neo4j
+ persistence-modules/spring-data-redis
+ spring-data-rest
+
+
+
+
+
+
+ persistence-modules/spring-data-solr
+ spring-dispatcher-servlet
+ spring-exceptions
+ spring-freemarker
+ persistence-modules/spring-hibernate-3
+ spring-hibernate4
+ persistence-modules/spring-hibernate-5
+ persistence-modules/spring-data-eclipselink
+ spring-integration
+ spring-jenkins-pipeline
+ spring-jersey
+ spring-jms
+ spring-jooq
+ persistence-modules/spring-jpa
+ spring-kafka
+ spring-katharsis
+ spring-ldap
+ spring-mockito
+ spring-mvc-forms-jsp
+ spring-mvc-forms-thymeleaf
+ spring-mvc-java
+ spring-mvc-velocity
+ spring-mvc-webflow
+ spring-mvc-xml
+ spring-mvc-kotlin
+ spring-protobuf
+ spring-quartz
+ spring-rest-angular
+ spring-rest-full
+ spring-rest-query-language
+ spring-rest
+ spring-rest-simple
+ spring-reactive-kotlin
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ integration-lite
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*ManualTest.java
+ **/*LiveTest.java
+
+
+ **/*IntegrationTest.java
+ **/*IntTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
+ parent-boot-1
+ parent-boot-2
+ parent-spring-4
+ parent-spring-5
+ parent-java
+
+ asm
+ atomix
+ apache-cayenne
+ aws
+ aws-lambda
+ akka-streams
+ algorithms
+ annotations
+ apache-cxf
+ apache-fop
+ apache-poi
+ apache-tika
+ apache-thrift
+ apache-curator
+ apache-zookeeper
+ apache-opennlp
+ autovalue
+ axon
+ azure
+ bootique
+ cdi
+
+ core-java-collections
+ core-java-io
+ core-java-8
+ core-groovy
+ core-java-concurrency
+ couchbase
+ deltaspike
+ dozer
+ ethereum
+ feign
+ flips
+ testing-modules/groovy-spock
+ google-cloud
+ gson
+ guava
+ guava-modules/guava-18
+ guava-modules/guava-19
+ guava-modules/guava-21
+ guice
+ disruptor
+ spring-static-resources
+ hazelcast
+ hbase
+ httpclient
+ hystrix
+ image-processing
+ immutables
+ influxdb
+ jackson
+ vavr
+ java-lite
+ java-numbers
+ java-rmi
+ java-vavr-stream
+ javax-servlets
+ javaxval
+ jaxb
+ javafx
+ jgroups
+ jee-7
+ jjwt
+ jpa-storedprocedure
+ jsf
+ json-path
+ json
+ jsoup
+ testing-modules/junit-5
+ jws
+ libraries-data
+ linkrest
+ logging-modules/log-mdc
+ logging-modules/log4j
+ logging-modules/log4j2
+ logging-modules/logback
+ lombok
+ mapstruct
+ metrics
+ maven
+ mesos-marathon
+ msf4j
+ testing-modules/mockito
+ testing-modules/mockito-2
+ testing-modules/mocks
+ mustache
+ mvn-wrapper
+ noexception
+ orientdb
+ osgi
+ orika
+ patterns
+ pdf
+ protobuffer
+ persistence-modules/querydsl
+ reactor-core
+ persistence-modules/redis
+ testing-modules/rest-assured
+ testing-modules/rest-testing
+ resteasy
+ rxjava
+ spring-swagger-codegen
+ testing-modules/selenium-junit-testng
+ persistence-modules/solr
+ spark-java
+ spring-4
+ spring-5-reactive
+ spring-5-mvc
+ spring-5-security
+ spring-activiti
+ spring-akka
+ spring-amqp
+ spring-all
+ spring-amqp-simple
+ spring-apache-camel
+ spring-batch
+ spring-bom
+ spring-boot-keycloak
+ spring-boot-bootstrap
+ spring-boot-admin
+ spring-boot-persistence
+ spring-boot-security
+ spring-boot-mvc
+ spring-boot-logging-log4j2
+ spring-cloud-data-flow
+ spring-cloud
+ spring-core
+ spring-cucumber
+ spring-ejb
+ spring-aop
+ spring-data-couchbase-2
+ persistence-modules/spring-data-dynamodb
+ spring-data-keyvalue
+ spring-data-mongodb
+ persistence-modules/spring-data-neo4j
+ persistence-modules/spring-data-redis
+ spring-data-rest
+ persistence-modules/spring-data-solr
+ spring-dispatcher-servlet
+ spring-exceptions
+ spring-freemarker
+ persistence-modules/spring-hibernate-3
+ spring-hibernate4
+ persistence-modules/spring-hibernate-5
+ persistence-modules/spring-data-eclipselink
+ spring-integration
+ spring-jenkins-pipeline
+ spring-jersey
+ jmeter
+ spring-jms
+ spring-jooq
+ persistence-modules/spring-jpa
+ spring-kafka
+ spring-katharsis
+ spring-ldap
+ spring-mockito
+ spring-mvc-forms-jsp
+ spring-mvc-forms-thymeleaf
+ spring-mvc-java
+ spring-mvc-velocity
+ spring-mvc-webflow
+ spring-mvc-xml
+ spring-mvc-kotlin
+ spring-protobuf
+ spring-quartz
+ spring-rest-angular
+ spring-rest-full
+ spring-rest-query-language
+ spring-rest
+ spring-rest-simple
+ spring-security-acl
+ spring-security-cache-control
+ spring-security-client/spring-security-jsp-authentication
+ spring-security-client/spring-security-jsp-authorize
+ spring-security-client/spring-security-jsp-config
+ spring-security-client/spring-security-mvc
+ spring-security-client/spring-security-thymeleaf-authentication
+ spring-security-client/spring-security-thymeleaf-authorize
+ spring-security-client/spring-security-thymeleaf-config
+ spring-security-core
+ spring-security-mvc-boot
+ spring-security-mvc-digest-auth
+ spring-security-mvc-ldap
+ spring-security-mvc-login
+ spring-security-mvc-persisted-remember-me
+ spring-security-mvc-session
+ spring-security-mvc-socket
+ spring-security-openid
+
+ spring-security-rest-basic-auth
+ spring-security-rest-custom
+ spring-security-rest
+ spring-security-sso
+ spring-security-x509
+ spring-session
+ spring-sleuth
+ spring-social-login
+ spring-spel
+ spring-state-machine
+ spring-thymeleaf
+ spring-userservice
+ spring-zuul
+ spring-reactor
+ spring-vertx
+ spring-jinq
+ spring-rest-embedded-tomcat
+ testing-modules/testing
+ testing-modules/testng
+ video-tutorials
+ xml
+ xmlunit-2
+ struts-2
+ apache-velocity
+ apache-solrj
+ rabbitmq
+ vertx
+ persistence-modules/spring-data-gemfire
+ mybatis
+ spring-drools
+ drools
+ persistence-modules/liquibase
+ spring-boot-property-exp
+ testing-modules/mockserver
+ testing-modules/test-containers
+ undertow
+ vertx-and-rxjava
+ saas
+ deeplearning4j
+ lucene
+ vraptor
+ persistence-modules/java-cockroachdb
+ spring-security-thymeleaf
+ persistence-modules/java-jdbi
+ jersey
+ java-spi
+ performance-tests
+ twilio
+ spring-boot-ctx-fluent
+ java-ee-8-security-api
+ spring-webflux-amqp
+ antlr
+ maven-archetype
+ apache-meecrowave
+
+
+
+
+
+
+
+
+
+
+
+
-
- integration
+ integration-heavy
+
@@ -497,64 +1134,90 @@
+
+
+ parent-boot-1
+ parent-boot-2
+ parent-spring-4
+ parent-spring-5
+ parent-java
+
+ libraries
+ geotools
+ jhipster/jhipster-monolithic
+ testing-modules/gatling
+ spring-boot
+ spring-boot-ops
+ spring-5
+ core-kotlin
+ core-java
+ google-web-toolkit
+ spring-security-mvc-custom
+ hibernate5
+ spring-data-elasticsearch
+
+
+
-
-
-
-
- org.apache.maven.plugins
- maven-jxr-plugin
- ${maven-jxr-plugin.version}
-
-
-
-
- UTF-8
- UTF-8
- refs/heads/master
- true
- false
- false
-
- 4.12
- 1.3
- 2.8.9
-
- 1.7.21
- 1.1.7
-
- 2.21.0
- 3.7.0
- 1.6.0
- 1.8
- 1.2.17
- 1.1
- 2.1.0.1
- 1.19
- 1.19
- 1.3
- 1.6.0
- 2.19.1
- 2.5
- 1.4
- 2.6
- 3.1.0
- 1.2
- 2.3.1
- 1.9.13
- 1.2
- 2.5.0
- 1.3
- 5.0.2
- 0.3.1
- 2.5.1
- 0.0.1
- 3.4
- 2.3
-
- 3.8
-
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-jxr-plugin
+ ${maven-jxr-plugin.version}
+
+
+
+
+
+ UTF-8
+ UTF-8
+ refs/heads/master
+ true
+ false
+ false
+
+ 4.12
+ 1.3
+ 2.8.9
+
+ 1.7.21
+ 1.1.7
+
+ 2.21.0
+ 3.7.0
+ 1.6.0
+ 1.8
+ 1.2.17
+ 1.1
+ 2.1.0.1
+ 1.19
+ 1.19
+ 1.3
+ 1.6.0
+ 2.19.1
+ 2.5
+ 1.4
+ 2.6
+ 3.1.0
+ 1.2
+ 2.3.1
+ 1.9.13
+ 1.2
+ 2.5.0
+ 1.3
+ 5.0.2
+ 0.3.1
+ 2.5.1
+ 0.0.1
+ 3.4
+ 2.3
+
+ 3.8
+
diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml
index 266399e295..33fcad4e1d 100644
--- a/spring-5-reactive/pom.xml
+++ b/spring-5-reactive/pom.xml
@@ -147,7 +147,15 @@
${project-reactor-test}
test
-
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+ org.springframework.security
+ spring-security-test
+ test
+
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java
new file mode 100644
index 0000000000..87efe72a1b
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java
@@ -0,0 +1,25 @@
+package com.baeldung.reactive.cors.annotated;
+
+import java.util.Collections;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
+import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration;
+import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
+import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration;
+
+@SpringBootApplication(exclude = { MongoAutoConfiguration.class,
+ MongoDataAutoConfiguration.class,
+ MongoReactiveDataAutoConfiguration.class,
+ MongoReactiveAutoConfiguration.class }
+)
+public class CorsOnAnnotatedElementsApplication {
+
+ public static void main(String[] args) {
+ SpringApplication app = new SpringApplication(CorsOnAnnotatedElementsApplication.class);
+ app.setDefaultProperties(Collections.singletonMap("server.port", "8081"));
+ app.run(args);
+ }
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnClassController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnClassController.java
new file mode 100644
index 0000000000..00bc93a101
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnClassController.java
@@ -0,0 +1,49 @@
+package com.baeldung.reactive.cors.annotated.controllers;
+
+import org.springframework.web.bind.annotation.CrossOrigin;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import reactor.core.publisher.Mono;
+
+@CrossOrigin(value = { "http://allowed-origin.com" }, allowedHeaders = { "Baeldung-Another-Allowed" }, maxAge = 900)
+@RestController
+@RequestMapping("/cors-on-controller")
+public class CorsOnClassController {
+
+ @PutMapping("/regular-endpoint")
+ public Mono corsDisabledEndpoint() {
+ return Mono.just("Regular endpoint");
+ }
+
+ @CrossOrigin
+ @PutMapping("/cors-enabled-endpoint")
+ public Mono corsEnabledEndpoint() {
+ return Mono.just("CORS enabled endpoint");
+ }
+
+ @CrossOrigin({ "http://another-allowed-origin.com" })
+ @PutMapping("/cors-enabled-origin-restrictive-endpoint")
+ public Mono corsEnabledOriginRestrictiveEndpoint() {
+ return Mono.just("CORS enabled endpoint - Origin Restrictive");
+ }
+
+ @CrossOrigin(allowedHeaders = { "Baeldung-Allowed" })
+ @PutMapping("/cors-enabled-header-restrictive-endpoint")
+ public Mono corsEnabledHeaderRestrictiveEndpoint() {
+ return Mono.just("CORS enabled endpoint - Header Restrictive");
+ }
+
+ @CrossOrigin(exposedHeaders = { "Baeldung-Exposed" })
+ @PutMapping("/cors-enabled-exposed-header-endpoint")
+ public Mono corsEnabledExposedHeadersEndpoint() {
+ return Mono.just("CORS enabled endpoint - Exposed Header");
+ }
+
+ @PutMapping("/cors-enabled-mixed-config-endpoint")
+ @CrossOrigin(allowedHeaders = { "Baeldung-Allowed", "Baeldung-Other-Allowed" }, exposedHeaders = { "Baeldung-Allowed", "Baeldung-Exposed" }, maxAge = 3600)
+ public Mono corsEnabledHeaderExposedEndpoint() {
+ return Mono.just("CORS enabled endpoint - Mixed Config");
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnMethodsController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnMethodsController.java
new file mode 100644
index 0000000000..3c72d25840
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnMethodsController.java
@@ -0,0 +1,48 @@
+package com.baeldung.reactive.cors.annotated.controllers;
+
+import org.springframework.web.bind.annotation.CrossOrigin;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import reactor.core.publisher.Mono;
+
+@RestController
+@RequestMapping("/cors-on-methods")
+public class CorsOnMethodsController {
+
+ @PutMapping("/cors-disabled-endpoint")
+ public Mono corsDisabledEndpoint() {
+ return Mono.just("CORS disabled endpoint");
+ }
+
+ @CrossOrigin
+ @PutMapping("/cors-enabled-endpoint")
+ public Mono corsEnabledEndpoint() {
+ return Mono.just("CORS enabled endpoint");
+ }
+
+ @CrossOrigin({ "http://allowed-origin.com" })
+ @PutMapping("/cors-enabled-origin-restrictive-endpoint")
+ public Mono corsEnabledOriginRestrictiveEndpoint() {
+ return Mono.just("CORS enabled endpoint - Origin Restrictive");
+ }
+
+ @CrossOrigin(allowedHeaders = { "Baeldung-Allowed" })
+ @PutMapping("/cors-enabled-header-restrictive-endpoint")
+ public Mono corsEnabledHeaderRestrictiveEndpoint() {
+ return Mono.just("CORS enabled endpoint - Header Restrictive");
+ }
+
+ @CrossOrigin(exposedHeaders = { "Baeldung-Exposed" })
+ @PutMapping("/cors-enabled-exposed-header-endpoint")
+ public Mono corsEnabledExposedHeadersEndpoint() {
+ return Mono.just("CORS enabled endpoint - Exposed Header");
+ }
+
+ @PutMapping("/cors-enabled-mixed-config-endpoint")
+ @CrossOrigin(allowedHeaders = { "Baeldung-Allowed", "Baeldung-Other-Allowed" }, exposedHeaders = { "Baeldung-Allowed", "Baeldung-Exposed" }, maxAge = 3600)
+ public Mono corsEnabledHeaderExposedEndpoint() {
+ return Mono.just("CORS enabled endpoint - Mixed Config");
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java
new file mode 100644
index 0000000000..8228944569
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java
@@ -0,0 +1,25 @@
+package com.baeldung.reactive.cors.global;
+
+import java.util.Collections;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
+import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration;
+import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
+import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration;
+
+@SpringBootApplication(exclude = { MongoAutoConfiguration.class,
+ MongoDataAutoConfiguration.class,
+ MongoReactiveDataAutoConfiguration.class,
+ MongoReactiveAutoConfiguration.class }
+)
+public class CorsGlobalConfigApplication {
+
+ public static void main(String[] args) {
+ SpringApplication app = new SpringApplication(CorsGlobalConfigApplication.class);
+ app.setDefaultProperties(Collections.singletonMap("server.port", "8082"));
+ app.run(args);
+ }
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/config/CorsGlobalConfiguration.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/config/CorsGlobalConfiguration.java
new file mode 100644
index 0000000000..92cd6ec50a
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/config/CorsGlobalConfiguration.java
@@ -0,0 +1,22 @@
+package com.baeldung.reactive.cors.global.config;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.reactive.config.CorsRegistry;
+import org.springframework.web.reactive.config.EnableWebFlux;
+import org.springframework.web.reactive.config.WebFluxConfigurer;
+
+@Configuration
+@EnableWebFlux
+public class CorsGlobalConfiguration implements WebFluxConfigurer {
+
+ @Override
+ public void addCorsMappings(CorsRegistry corsRegistry) {
+ corsRegistry.addMapping("/**")
+ .allowedOrigins("http://allowed-origin.com")
+ .allowedMethods("PUT")
+ .allowedHeaders("Baeldung-Allowed", "Baledung-Another-Allowed")
+ .exposedHeaders("Baeldung-Allowed", "Baeldung-Exposed")
+ .maxAge(3600);
+ }
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java
new file mode 100644
index 0000000000..b6341c9af1
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java
@@ -0,0 +1,24 @@
+package com.baeldung.reactive.cors.global.controllers;
+
+import org.springframework.web.bind.annotation.CrossOrigin;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import reactor.core.publisher.Mono;
+
+@RestController
+@RequestMapping("/cors-on-global-config-and-more")
+public class FurtherCorsConfigsController {
+
+ @DeleteMapping("/further-mixed-config-endpoint")
+ @CrossOrigin(methods = { RequestMethod.DELETE },
+ allowedHeaders = { "Baeldung-Other-Allowed" },
+ exposedHeaders = { "Baeldung-Other-Exposed" }
+ )
+ public Mono corsEnabledHeaderExposedEndpoint() {
+ return Mono.just("CORS Global Configured + Request Configs.");
+ }
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java
new file mode 100644
index 0000000000..5945cfc9f2
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java
@@ -0,0 +1,23 @@
+package com.baeldung.reactive.cors.global.controllers;
+
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import reactor.core.publisher.Mono;
+
+@RestController
+@RequestMapping("/cors-on-global-config")
+public class RegularRestController {
+
+ @PutMapping("/regular-put-endpoint")
+ public Mono regularPutEndpoint() {
+ return Mono.just("Regular PUT endpoint");
+ }
+
+ @DeleteMapping("/regular-delete-endpoint")
+ public Mono regularDeleteEndpoint() {
+ return Mono.just("Regular DELETE endpoint");
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java
new file mode 100644
index 0000000000..e6e32d7cc8
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java
@@ -0,0 +1,18 @@
+package com.baeldung.reactive.cors.global.functional.handlers;
+
+import org.springframework.stereotype.Component;
+import org.springframework.web.reactive.function.server.ServerRequest;
+import org.springframework.web.reactive.function.server.ServerResponse;
+
+import reactor.core.publisher.Mono;
+
+@Component
+public class FunctionalHandler {
+
+ public Mono useHandler(final ServerRequest request) {
+ final String responseMessage = "CORS GLOBAL CONFIG IS NOT EFFECTIVE ON FUNCTIONAL ENDPOINTS!!!";
+
+ return ServerResponse.ok()
+ .body(Mono.just(responseMessage), String.class);
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java
new file mode 100644
index 0000000000..19621a9e97
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java
@@ -0,0 +1,20 @@
+package com.baeldung.reactive.cors.global.functional.routers;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.reactive.function.server.RequestPredicates;
+import org.springframework.web.reactive.function.server.RouterFunction;
+import org.springframework.web.reactive.function.server.RouterFunctions;
+import org.springframework.web.reactive.function.server.ServerResponse;
+
+import com.baeldung.reactive.cors.global.functional.handlers.FunctionalHandler;
+
+@Configuration
+public class CorsRouterFunctions {
+
+ @Bean
+ public RouterFunction responseHeaderRoute(@Autowired FunctionalHandler handler) {
+ return RouterFunctions.route(RequestPredicates.PUT("/global-config-on-functional/cors-disabled-functional-endpoint"), handler::useHandler);
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java
new file mode 100644
index 0000000000..38140c0d71
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java
@@ -0,0 +1,25 @@
+package com.baeldung.reactive.cors.webfilter;
+
+import java.util.Collections;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
+import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration;
+import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
+import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration;
+
+@SpringBootApplication(exclude = { MongoAutoConfiguration.class,
+ MongoDataAutoConfiguration.class,
+ MongoReactiveDataAutoConfiguration.class,
+ MongoReactiveAutoConfiguration.class }
+)
+public class CorsWebFilterApplication {
+
+ public static void main(String[] args) {
+ SpringApplication app = new SpringApplication(CorsWebFilterApplication.class);
+ app.setDefaultProperties(Collections.singletonMap("server.port", "8083"));
+ app.run(args);
+ }
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/config/CorsWebFilterConfig.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/config/CorsWebFilterConfig.java
new file mode 100644
index 0000000000..55fbcc2903
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/config/CorsWebFilterConfig.java
@@ -0,0 +1,29 @@
+package com.baeldung.reactive.cors.webfilter.config;
+
+import java.util.Arrays;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.reactive.CorsWebFilter;
+import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
+import org.springframework.web.util.pattern.PathPatternParser;
+
+@Configuration
+public class CorsWebFilterConfig {
+
+ @Bean
+ CorsWebFilter corsWebFilter() {
+ CorsConfiguration corsConfig = new CorsConfiguration();
+ corsConfig.setAllowedOrigins(Arrays.asList("http://allowed-origin.com"));
+ corsConfig.setMaxAge(8000L);
+ corsConfig.addAllowedMethod("PUT");
+ corsConfig.addAllowedHeader("Baeldung-Allowed");
+
+ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
+ source.registerCorsConfiguration("/**", corsConfig);
+
+ return new CorsWebFilter(source);
+ }
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java
new file mode 100644
index 0000000000..4f9b9bd037
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java
@@ -0,0 +1,26 @@
+package com.baeldung.reactive.cors.webfilter.controllers;
+
+import org.springframework.web.bind.annotation.CrossOrigin;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import reactor.core.publisher.Mono;
+
+@RestController
+@RequestMapping("/web-filter-and-more-on-annotated")
+public class FurtherCorsConfigsController {
+
+ @DeleteMapping("/further-mixed-config-endpoint")
+ @CrossOrigin(methods = { RequestMethod.DELETE },
+ allowedHeaders = { "Baeldung-Other-Allowed" },
+ exposedHeaders = { "Baeldung-Other-Exposed" }
+ )
+ public Mono corsEnabledHeaderExposedEndpoint() {
+ final String responseMessage = "CORS @CrossOrigin IS NOT EFFECTIVE with WebFilter!!!";
+
+ return Mono.just(responseMessage);
+ }
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java
new file mode 100644
index 0000000000..6985810aa5
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java
@@ -0,0 +1,23 @@
+package com.baeldung.reactive.cors.webfilter.controllers;
+
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import reactor.core.publisher.Mono;
+
+@RestController
+@RequestMapping("/web-filter-on-annotated")
+public class RegularRestController {
+
+ @PutMapping("/regular-put-endpoint")
+ public Mono regularPutEndpoint() {
+ return Mono.just("Regular PUT endpoint");
+ }
+
+ @DeleteMapping("/regular-delete-endpoint")
+ public Mono regularDeleteEndpoint() {
+ return Mono.just("Regular DELETE endpoint");
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/handlers/CorsWithWebFilterHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/handlers/CorsWithWebFilterHandler.java
new file mode 100644
index 0000000000..04e4602049
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/handlers/CorsWithWebFilterHandler.java
@@ -0,0 +1,16 @@
+package com.baeldung.reactive.cors.webfilter.functional.handlers;
+
+import org.springframework.stereotype.Component;
+import org.springframework.web.reactive.function.server.ServerRequest;
+import org.springframework.web.reactive.function.server.ServerResponse;
+
+import reactor.core.publisher.Mono;
+
+@Component
+public class CorsWithWebFilterHandler {
+
+ public Mono useHandler(final ServerRequest request) {
+ return ServerResponse.ok()
+ .body(Mono.just("Functional Endpoint"), String.class);
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java
new file mode 100644
index 0000000000..a3905bb79f
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java
@@ -0,0 +1,20 @@
+package com.baeldung.reactive.cors.webfilter.functional.routers;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.reactive.function.server.RequestPredicates;
+import org.springframework.web.reactive.function.server.RouterFunction;
+import org.springframework.web.reactive.function.server.RouterFunctions;
+import org.springframework.web.reactive.function.server.ServerResponse;
+
+import com.baeldung.reactive.cors.webfilter.functional.handlers.CorsWithWebFilterHandler;
+
+@Configuration
+public class CorsWithWebFilterRouterFunctions {
+
+ @Bean
+ public RouterFunction responseHeaderRoute(@Autowired CorsWithWebFilterHandler handler) {
+ return RouterFunctions.route(RequestPredicates.PUT("/web-filter-on-functional/functional-endpoint"), handler::useHandler);
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java
new file mode 100644
index 0000000000..6a03555654
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java
@@ -0,0 +1,17 @@
+package com.baeldung.reactive.webflux;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+public class Employee {
+
+ private String id;
+ private String name;
+
+ // standard getters and setters
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeConfig.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeConfig.java
new file mode 100644
index 0000000000..082be68698
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeConfig.java
@@ -0,0 +1,33 @@
+package com.baeldung.reactive.webflux;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.reactive.HandlerMapping;
+import org.springframework.web.reactive.config.EnableWebFlux;
+import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
+import org.springframework.web.reactive.socket.WebSocketHandler;
+import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
+
+@Configuration
+@EnableWebFlux
+public class EmployeeConfig {
+
+ @Bean
+ public HandlerMapping handlerMapping() {
+ Map map = new HashMap<>();
+ map.put("/employee-feed", new EmployeeWebSocketHandler());
+
+ SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
+ mapping.setUrlMap(map);
+ mapping.setOrder(10);
+ return mapping;
+ }
+
+ @Bean
+ public WebSocketHandlerAdapter handlerAdapter() {
+ return new WebSocketHandlerAdapter();
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeController.java
new file mode 100644
index 0000000000..98b16dafab
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeController.java
@@ -0,0 +1,38 @@
+package com.baeldung.reactive.webflux;
+
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+@RestController
+@RequestMapping("/employees")
+public class EmployeeController {
+
+ private EmployeeRepository employeeRepository;
+
+ public EmployeeController(EmployeeRepository employeeRepository) {
+ this.employeeRepository = employeeRepository;
+ }
+
+ @GetMapping("/{id}")
+ private Mono getEmployeeById(@PathVariable String id) {
+ return employeeRepository.findEmployeeById(id);
+ }
+
+ @GetMapping
+ private Flux getAllEmployees() {
+ return employeeRepository.findAllEmployees();
+ }
+
+ @PostMapping("/update")
+ private Mono updateEmployee(@RequestBody Employee employee) {
+ return employeeRepository.updateEmployee(employee);
+ }
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java
new file mode 100644
index 0000000000..7be088f073
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java
@@ -0,0 +1,11 @@
+package com.baeldung.reactive.webflux;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class EmployeeCreationEvent {
+ private String employeeId;
+ private String creationTime;
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java
new file mode 100644
index 0000000000..a407c76fa8
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java
@@ -0,0 +1,64 @@
+package com.baeldung.reactive.webflux;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.springframework.stereotype.Repository;
+
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+@Repository
+public class EmployeeRepository {
+
+ static Map employeeData;
+
+ static Map employeeAccessData;
+
+ static
+ {
+ employeeData = new HashMap<>();
+ employeeData.put("1",new Employee("1","Employee 1"));
+ employeeData.put("2",new Employee("2","Employee 2"));
+ employeeData.put("3",new Employee("3","Employee 3"));
+ employeeData.put("4",new Employee("4","Employee 4"));
+ employeeData.put("5",new Employee("5","Employee 5"));
+ employeeData.put("6",new Employee("6","Employee 6"));
+ employeeData.put("7",new Employee("7","Employee 7"));
+ employeeData.put("8",new Employee("8","Employee 8"));
+ employeeData.put("9",new Employee("9","Employee 9"));
+ employeeData.put("10",new Employee("10","Employee 10"));
+
+ employeeAccessData=new HashMap<>();
+ employeeAccessData.put("1", "Employee 1 Access Key");
+ employeeAccessData.put("2", "Employee 2 Access Key");
+ employeeAccessData.put("3", "Employee 3 Access Key");
+ employeeAccessData.put("4", "Employee 4 Access Key");
+ employeeAccessData.put("5", "Employee 5 Access Key");
+ employeeAccessData.put("6", "Employee 6 Access Key");
+ employeeAccessData.put("7", "Employee 7 Access Key");
+ employeeAccessData.put("8", "Employee 8 Access Key");
+ employeeAccessData.put("9", "Employee 9 Access Key");
+ employeeAccessData.put("10", "Employee 10 Access Key");
+ }
+
+ public Mono findEmployeeById(String id)
+ {
+ return Mono.just(employeeData.get(id));
+ }
+
+ public Flux findAllEmployees()
+ {
+ return Flux.fromIterable(employeeData.values());
+ }
+
+ public Mono updateEmployee(Employee employee)
+ {
+ Employee existingEmployee=employeeData.get(employee.getId());
+ if(existingEmployee!=null)
+ {
+ existingEmployee.setName(employee.getName());
+ }
+ return Mono.just(existingEmployee);
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeSpringApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeSpringApplication.java
new file mode 100644
index 0000000000..54b23a18de
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeSpringApplication.java
@@ -0,0 +1,17 @@
+package com.baeldung.reactive.webflux;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class EmployeeSpringApplication {
+
+ public static void main(String[] args) {
+
+ SpringApplication.run(EmployeeSpringApplication.class, args);
+
+ EmployeeWebClient employeeWebClient = new EmployeeWebClient();
+ employeeWebClient.consume();
+ }
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebClient.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebClient.java
new file mode 100644
index 0000000000..45d42ecda9
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebClient.java
@@ -0,0 +1,28 @@
+package com.baeldung.reactive.webflux;
+
+import org.springframework.web.reactive.function.client.WebClient;
+
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+public class EmployeeWebClient {
+
+ WebClient client = WebClient.create("http://localhost:8080");
+
+ public void consume() {
+
+ Mono employeeMono = client.get()
+ .uri("/employees/{id}", "1")
+ .retrieve()
+ .bodyToMono(Employee.class);
+
+ employeeMono.subscribe(System.out::println);
+
+ Flux employeeFlux = client.get()
+ .uri("/employees")
+ .retrieve()
+ .bodyToFlux(Employee.class);
+
+ employeeFlux.subscribe(System.out::println);
+ }
+}
\ No newline at end of file
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSecurityConfig.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSecurityConfig.java
new file mode 100644
index 0000000000..7922e6ba44
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSecurityConfig.java
@@ -0,0 +1,38 @@
+package com.baeldung.reactive.webflux;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.http.HttpMethod;
+import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
+import org.springframework.security.config.web.server.ServerHttpSecurity;
+import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.web.server.SecurityWebFilterChain;
+
+@EnableWebFluxSecurity
+public class EmployeeWebSecurityConfig {
+
+ @Bean
+ public MapReactiveUserDetailsService userDetailsService() {
+ UserDetails user = User.withDefaultPasswordEncoder()
+ .username("admin")
+ .password("password")
+ .roles("ADMIN")
+ .build();
+ return new MapReactiveUserDetailsService(user);
+ }
+
+ @Bean
+ public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
+ http.csrf()
+ .disable()
+ .authorizeExchange()
+ .pathMatchers(HttpMethod.POST, "/employees/update")
+ .hasRole("ADMIN")
+ .pathMatchers("/**")
+ .permitAll()
+ .and()
+ .httpBasic();
+ return http.build();
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketClient.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketClient.java
new file mode 100644
index 0000000000..4571cadc47
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketClient.java
@@ -0,0 +1,21 @@
+package com.baeldung.reactive.webflux;
+
+import java.net.URI;
+
+import org.springframework.web.reactive.socket.WebSocketMessage;
+import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
+import org.springframework.web.reactive.socket.client.WebSocketClient;
+
+public class EmployeeWebSocketClient {
+
+ public static void main(String[] args) {
+
+ WebSocketClient client = new ReactorNettyWebSocketClient();
+
+ client.execute(URI.create("ws://localhost:8080/employee-feed"), session -> session.receive()
+ .map(WebSocketMessage::getPayloadAsText)
+ .doOnNext(System.out::println)
+ .then())
+ .block(); // to subscribe and return the value
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java
new file mode 100644
index 0000000000..caa2a38b65
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java
@@ -0,0 +1,39 @@
+package com.baeldung.reactive.webflux;
+
+import static java.time.LocalDateTime.now;
+import static java.util.UUID.randomUUID;
+
+import java.time.Duration;
+
+import org.springframework.stereotype.Component;
+import org.springframework.web.reactive.socket.WebSocketHandler;
+import org.springframework.web.reactive.socket.WebSocketSession;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+@Component
+public class EmployeeWebSocketHandler implements WebSocketHandler {
+
+ ObjectMapper om = new ObjectMapper();
+
+ @Override
+ public Mono handle(WebSocketSession webSocketSession) {
+
+ Flux employeeCreationEvent = Flux.generate(sink -> {
+ EmployeeCreationEvent event = new EmployeeCreationEvent(randomUUID().toString(), now().toString());
+ try {
+ sink.next(om.writeValueAsString(event));
+ } catch (JsonProcessingException e) {
+ sink.error(e);
+ }
+ });
+
+ return webSocketSession.send(employeeCreationEvent
+ .map(webSocketSession::textMessage)
+ .delayElements(Duration.ofSeconds(1)));
+ }
+}
diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java
new file mode 100644
index 0000000000..0043d62e5a
--- /dev/null
+++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java
@@ -0,0 +1,147 @@
+package com.baeldung.reactive.cors;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.reactive.server.WebTestClient;
+import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+public class CorsOnAnnotatedElementsLiveTest {
+
+ private static final String BASE_URL = "http://localhost:8081";
+ private static final String BASE_CORS_ON_METHODS_URL = "/cors-on-methods";
+ private static final String BASE_CORS_ON_CONTROLLER_URL = "/cors-on-controller";
+ private static final String CONTROLLER_CORS_ALLOWED_ORIGIN = "http://allowed-origin.com";
+ private static final String CORS_DEFAULT_ORIGIN = "http://default-origin.com";
+
+ private static WebTestClient client;
+
+ @BeforeAll
+ public static void setup() {
+ client = WebTestClient.bindToServer()
+ .baseUrl(BASE_URL)
+ .defaultHeader("Origin", CORS_DEFAULT_ORIGIN)
+ .build();
+ }
+
+ @Test
+ public void whenRequestingMethodCorsEnabledEndpoint_thenObtainResponseWithCorsHeaders() {
+ ResponseSpec response = client.put()
+ .uri(BASE_CORS_ON_METHODS_URL + "/cors-enabled-endpoint")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Origin", "*");
+ }
+
+ @Test
+ public void whenPreflightMethodCorsEnabled_thenObtainResponseWithCorsHeaders() {
+ ResponseSpec response = client.options()
+ .uri(BASE_CORS_ON_METHODS_URL + "/cors-enabled-endpoint")
+ .header("Access-Control-Request-Method", "PUT")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Origin", "*");
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Methods", "PUT");
+ response.expectHeader()
+ .exists("Access-Control-Max-Age");
+ }
+
+ @Test
+ public void whenRequestingMethodCorsDisabledEndpoint_thenObtainResponseWithoutCorsHeaders() {
+ ResponseSpec response = client.put()
+ .uri(BASE_CORS_ON_METHODS_URL + "/cors-disabled-put-endpoint")
+ .exchange();
+
+ response.expectHeader()
+ .doesNotExist("Access-Control-Allow-Origin");
+ }
+
+ @Test
+ public void whenRequestingMethodCorsRestrictiveOrigin_thenObtainForbiddenResponse() {
+ ResponseSpec response = client.put()
+ .uri(BASE_CORS_ON_METHODS_URL + "/cors-enabled-origin-restrictive-endpoint")
+ .exchange();
+
+ response.expectStatus()
+ .isForbidden();
+ }
+
+ @Test
+ public void whenPreflightMethodCorsRestrictiveOrigin_thenObtainForbiddenResponse() {
+ ResponseSpec response = client.options()
+ .uri(BASE_CORS_ON_METHODS_URL + "/cors-enabled-origin-restrictive-endpoint")
+ .header("Access-Control-Request-Method", "PUT")
+ .exchange();
+
+ response.expectStatus()
+ .isForbidden();
+ }
+
+ @Test
+ public void whenPreflightMethodCorsRestrictiveHeader_thenObtainResponseWithAllowedHeaders() {
+ ResponseSpec response = client.options()
+ .uri(BASE_CORS_ON_METHODS_URL + "/cors-enabled-header-restrictive-endpoint")
+ .header("Access-Control-Request-Method", "PUT")
+ .header("Access-Control-Request-Headers", "Baeldung-Not-Allowed, Baeldung-Allowed")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Headers", "Baeldung-Allowed");
+ }
+
+ @Test
+ public void whenPreflightControllerCorsRegularEndpoint_thenObtainResponseWithCorsHeaders() {
+ ResponseSpec response = client.options()
+ .uri(BASE_CORS_ON_CONTROLLER_URL + "/regular-endpoint")
+ .header("Origin", CONTROLLER_CORS_ALLOWED_ORIGIN)
+ .header("Access-Control-Request-Method", "PUT")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Origin", CONTROLLER_CORS_ALLOWED_ORIGIN);
+ }
+
+ @Test
+ public void whenPreflightControllerCorsRestrictiveOrigin_thenObtainResponseWithCorsHeaders() {
+ ResponseSpec response = client.options()
+ .uri(BASE_CORS_ON_CONTROLLER_URL + "/cors-enabled-origin-restrictive-endpoint")
+ .header("Origin", CONTROLLER_CORS_ALLOWED_ORIGIN)
+ .header("Access-Control-Request-Method", "PUT")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Origin", CONTROLLER_CORS_ALLOWED_ORIGIN);
+ }
+
+ @Test
+ public void whenPreflightControllerCorsRestrictiveOriginWithAnotherAllowedOrigin_thenObtainResponseWithCorsHeaders() {
+ final String anotherAllowedOrigin = "http://another-allowed-origin.com";
+ ResponseSpec response = client.options()
+ .uri(BASE_CORS_ON_CONTROLLER_URL + "/cors-enabled-origin-restrictive-endpoint")
+ .header("Origin", anotherAllowedOrigin)
+ .header("Access-Control-Request-Method", "PUT")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Origin", anotherAllowedOrigin);
+ }
+
+ @Test
+ public void whenPreflightControllerCorsExposingHeaders_thenObtainResponseWithCorsHeaders() {
+ ResponseSpec response = client.options()
+ .uri(BASE_CORS_ON_CONTROLLER_URL + "/cors-enabled-exposed-header-endpoint")
+ .header("Origin", CONTROLLER_CORS_ALLOWED_ORIGIN)
+ .header("Access-Control-Request-Method", "PUT")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Expose-Headers", "Baeldung-Exposed");
+ }
+}
diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java
new file mode 100644
index 0000000000..39927af4c3
--- /dev/null
+++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java
@@ -0,0 +1,99 @@
+package com.baeldung.reactive.cors;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.reactive.server.WebTestClient;
+import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+public class CorsOnGlobalConfigLiveTest {
+
+ private static final String BASE_URL = "http://localhost:8082";
+ private static final String BASE_REGULAR_URL = "/cors-on-global-config";
+ private static final String BASE_EXTRA_CORS_CONFIG_URL = "/cors-on-global-config-and-more";
+ private static final String BASE_FUNCTIONALS_URL = "/global-config-on-functional";
+ private static final String CORS_DEFAULT_ORIGIN = "http://allowed-origin.com";
+
+ private static WebTestClient client;
+
+ @BeforeAll
+ public static void setup() {
+ client = WebTestClient.bindToServer()
+ .baseUrl(BASE_URL)
+ .defaultHeader("Origin", CORS_DEFAULT_ORIGIN)
+ .build();
+ }
+
+ @Test
+ public void whenRequestingRegularEndpoint_thenObtainResponseWithCorsHeaders() {
+ ResponseSpec response = client.put()
+ .uri(BASE_REGULAR_URL + "/regular-put-endpoint")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Origin", CORS_DEFAULT_ORIGIN);
+ }
+
+ @Test
+ public void whenRequestingRegularDeleteEndpoint_thenObtainForbiddenResponse() {
+ ResponseSpec response = client.delete()
+ .uri(BASE_REGULAR_URL + "/regular-delete-endpoint")
+ .exchange();
+
+ response.expectStatus()
+ .isForbidden();
+ }
+
+ @Test
+ public void whenPreflightAllowedDeleteEndpoint_thenObtainResponseWithCorsHeaders() {
+ ResponseSpec response = client.options()
+ .uri(BASE_EXTRA_CORS_CONFIG_URL + "/further-mixed-config-endpoint")
+ .header("Access-Control-Request-Method", "DELETE")
+ .header("Access-Control-Request-Headers", "Baeldung-Not-Allowed, Baeldung-Allowed, Baeldung-Other-Allowed")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Origin", CORS_DEFAULT_ORIGIN);
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Methods", "PUT,DELETE");
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Headers", "Baeldung-Allowed, Baeldung-Other-Allowed");
+ response.expectHeader()
+ .exists("Access-Control-Max-Age");
+ }
+
+ @Test
+ public void whenRequestAllowedDeleteEndpoint_thenObtainResponseWithCorsHeaders() {
+ ResponseSpec response = client.delete()
+ .uri(BASE_EXTRA_CORS_CONFIG_URL + "/further-mixed-config-endpoint")
+ .exchange();
+
+ response.expectStatus()
+ .isOk();
+ }
+
+ @Test
+ public void whenPreflightFunctionalEndpoint_thenObtain404Response() {
+ ResponseSpec response = client.options()
+ .uri(BASE_FUNCTIONALS_URL + "/cors-disabled-functional-endpoint")
+ .header("Access-Control-Request-Method", "PUT")
+ .exchange();
+
+ response.expectStatus()
+ .isNotFound();
+ }
+
+ @Test
+ public void whenRequestFunctionalEndpoint_thenObtainResponseWithCorsHeaders() {
+ ResponseSpec response = client.put()
+ .uri(BASE_FUNCTIONALS_URL + "/cors-disabled-functional-endpoint")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Origin", CORS_DEFAULT_ORIGIN);
+ }
+}
diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java
new file mode 100644
index 0000000000..e5a3c8a99a
--- /dev/null
+++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java
@@ -0,0 +1,96 @@
+package com.baeldung.reactive.cors;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.reactive.server.WebTestClient;
+import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+public class CorsOnWebFilterLiveTest {
+
+ private static final String BASE_URL = "http://localhost:8083";
+ private static final String BASE_REGULAR_URL = "/web-filter-on-annotated";
+ private static final String BASE_EXTRA_CORS_CONFIG_URL = "/web-filter-and-more-on-annotated";
+ private static final String BASE_FUNCTIONALS_URL = "/web-filter-on-functional";
+ private static final String CORS_DEFAULT_ORIGIN = "http://allowed-origin.com";
+
+ private static WebTestClient client;
+
+ @BeforeAll
+ public static void setup() {
+ client = WebTestClient.bindToServer()
+ .baseUrl(BASE_URL)
+ .defaultHeader("Origin", CORS_DEFAULT_ORIGIN)
+ .build();
+ }
+
+ @Test
+ public void whenRequestingRegularEndpoint_thenObtainResponseWithCorsHeaders() {
+ ResponseSpec response = client.put()
+ .uri(BASE_REGULAR_URL + "/regular-put-endpoint")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Origin", CORS_DEFAULT_ORIGIN);
+ }
+
+ @Test
+ public void whenRequestingRegularDeleteEndpoint_thenObtainForbiddenResponse() {
+ ResponseSpec response = client.delete()
+ .uri(BASE_REGULAR_URL + "/regular-delete-endpoint")
+ .exchange();
+
+ response.expectStatus()
+ .isForbidden();
+ }
+
+ @Test
+ public void whenPreflightDeleteEndpointWithExtraConfigs_thenObtainForbiddenResponse() {
+ ResponseSpec response = client.options()
+ .uri(BASE_EXTRA_CORS_CONFIG_URL + "/further-mixed-config-endpoint")
+ .header("Access-Control-Request-Method", "DELETE")
+ .exchange();
+
+ response.expectStatus()
+ .isForbidden();
+ }
+
+ @Test
+ public void whenRequestDeleteEndpointWithExtraConfigs_thenObtainForbiddenResponse() {
+ ResponseSpec response = client.delete()
+ .uri(BASE_EXTRA_CORS_CONFIG_URL + "/further-mixed-config-endpoint")
+ .exchange();
+
+ response.expectStatus()
+ .isForbidden();
+ }
+
+ @Test
+ public void whenPreflightFunctionalEndpoint_thenObtain404Response() {
+ ResponseSpec response = client.options()
+ .uri(BASE_FUNCTIONALS_URL + "/functional-endpoint")
+ .header("Access-Control-Request-Method", "PUT")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Origin", CORS_DEFAULT_ORIGIN);
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Methods", "PUT");
+ response.expectHeader()
+ .valueEquals("Access-Control-Max-Age", "8000");
+ }
+
+ @Test
+ public void whenRequestFunctionalEndpoint_thenObtainResponseWithCorsHeaders() {
+ ResponseSpec response = client.put()
+ .uri(BASE_FUNCTIONALS_URL + "/functional-endpoint")
+ .exchange();
+
+ response.expectHeader()
+ .valueEquals("Access-Control-Allow-Origin", CORS_DEFAULT_ORIGIN);
+ }
+}
diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerUnitTest.java
new file mode 100644
index 0000000000..640f28c331
--- /dev/null
+++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerUnitTest.java
@@ -0,0 +1,72 @@
+package com.baeldung.reactive.webflux;
+
+import static org.mockito.BDDMockito.given;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.reactive.server.WebTestClient;
+
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class EmployeeControllerUnitTest {
+
+ @Autowired
+ private WebTestClient testClient;
+
+ @MockBean
+ private EmployeeRepository employeeRepository;
+
+ @Test
+ public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() {
+
+ Employee employee = new Employee("1", "Employee 1 Name");
+
+ given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee));
+ testClient.get()
+ .uri("/employees/1")
+ .exchange()
+ .expectStatus()
+ .isOk()
+ .expectBody(Employee.class)
+ .isEqualTo(employee);
+ }
+
+ @Test
+ public void whenGetAllEmployees_thenCorrectEmployees() {
+
+ List employeeList = new ArrayList<>();
+
+ Employee employee1 = new Employee("1", "Employee 1 Name");
+ Employee employee2 = new Employee("2", "Employee 2 Name");
+ Employee employee3 = new Employee("3", "Employee 3 Name");
+
+ employeeList.add(employee1);
+ employeeList.add(employee2);
+ employeeList.add(employee3);
+
+ Flux employeeFlux = Flux.fromIterable(employeeList);
+
+ given(employeeRepository.findAllEmployees()).willReturn(employeeFlux);
+ testClient.get()
+ .uri("/employees")
+ .exchange()
+ .expectStatus()
+ .isOk()
+ .expectBodyList(Employee.class)
+ .hasSize(3)
+ .isEqualTo(employeeList);
+ }
+}
diff --git a/spring-amqp-simple/src/test/java/broadcast/BroadcastMessageControllerIntegrationTest.java b/spring-amqp-simple/src/test/java/broadcast/BroadcastMessageControllerIntegrationTest.java
deleted file mode 100644
index c3be7f1ede..0000000000
--- a/spring-amqp-simple/src/test/java/broadcast/BroadcastMessageControllerIntegrationTest.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package broadcast;
-
-import com.baeldung.springamqpsimple.broadcast.BroadcastConfig;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.amqp.rabbit.core.RabbitTemplate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.test.mock.mockito.MockBean;
-import org.springframework.boot.test.web.client.TestRestTemplate;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.test.context.ActiveProfiles;
-import org.springframework.test.context.junit4.SpringRunner;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.*;
-import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
-
-@RunWith(SpringRunner.class)
-@ActiveProfiles("test")
-@SpringBootTest(webEnvironment = RANDOM_PORT)
-public class BroadcastMessageControllerIntegrationTest {
-
- @Autowired
- private TestRestTemplate restTemplate;
-
- @MockBean
- private RabbitTemplate rabbitTemplate;
-
- @Test
- public void whenPostingMessage_thenMessageIsCreated() {
- final String message = "Hello World!";
- ResponseEntity responseEntity = restTemplate.postForEntity("/broadcast", message, Void.class);
-
- assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode());
- }
-
- @Test
- public void whenPostingMessage_thenMessageIsSentToBroker() {
- final String message = "Hello World!";
- restTemplate.postForEntity("/broadcast", message, Void.class);
-
- verify(rabbitTemplate).convertAndSend(BroadcastConfig.fanoutExchangeName, "", message);
- verify(rabbitTemplate).convertAndSend(BroadcastConfig.topicExchangeName, "user.not-important.info", message);
- verify(rabbitTemplate).convertAndSend(BroadcastConfig.topicExchangeName, "user.important.error", message);
- }
-}
\ No newline at end of file
diff --git a/spring-amqp-simple/src/test/java/com/baeldung/springamqpsimple/MessageControllerIntegrationTest.java b/spring-amqp-simple/src/test/java/com/baeldung/springamqpsimple/MessageControllerIntegrationTest.java
deleted file mode 100644
index a053edaa0e..0000000000
--- a/spring-amqp-simple/src/test/java/com/baeldung/springamqpsimple/MessageControllerIntegrationTest.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.baeldung.springamqpsimple;
-
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.amqp.rabbit.core.RabbitTemplate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.test.mock.mockito.MockBean;
-import org.springframework.boot.test.web.client.TestRestTemplate;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.test.context.ActiveProfiles;
-import org.springframework.test.context.junit4.SpringRunner;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.verify;
-import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
-
-@RunWith(SpringRunner.class)
-@ActiveProfiles("test")
-@SpringBootTest(webEnvironment = RANDOM_PORT)
-public class MessageControllerIntegrationTest {
-
- @Autowired
- private TestRestTemplate restTemplate;
-
- @MockBean
- private RabbitTemplate rabbitTemplate;
-
- @Test
- public void whenPostingMessage_thenMessageIsCreated() {
- final String message = "Hello World!";
- ResponseEntity responseEntity = restTemplate.postForEntity("/messages", message, Void.class);
-
- assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode());
- }
-
- @Test
- public void whenPostingMessage_thenMessageIsSentToBroker() {
- final String message = "Hello World!";
- restTemplate.postForEntity("/messages", message, Void.class);
-
- verify(rabbitTemplate).convertAndSend(SpringAmqpConfig.queueName, message);
- }
-}
\ No newline at end of file
diff --git a/spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java b/spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java
new file mode 100644
index 0000000000..3b5a8be088
--- /dev/null
+++ b/spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java
@@ -0,0 +1,23 @@
+package com.baeldung.domain;
+
+import javax.persistence.*;
+import java.util.Date;
+
+@Entity
+public class Article {
+
+ @Id
+ @GeneratedValue
+ private Integer id;
+ @Temporal(TemporalType.DATE)
+ private Date publicationDate;
+ @Temporal(TemporalType.TIME)
+ private Date publicationTime;
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date creationDateTime;
+
+ public Integer getId() {
+ return id;
+ }
+
+}
diff --git a/spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java b/spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java
new file mode 100644
index 0000000000..4e1b109430
--- /dev/null
+++ b/spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java
@@ -0,0 +1,22 @@
+package com.baeldung.repository;
+
+import com.baeldung.domain.Article;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+
+import java.util.Date;
+import java.util.List;
+
+public interface ArticleRepository extends JpaRepository {
+
+ List findAllByPublicationDate(Date publicationDate);
+
+ List findAllByPublicationTimeBetween(Date publicationTimeStart,
+ Date publicationTimeEnd);
+
+ @Query("select a from Article a where a.creationDateTime <= :creationDateTime")
+ List findAllWithCreationDateTimeBefore(
+ @Param("creationDateTime") Date creationDateTime);
+
+}
diff --git a/spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java
new file mode 100644
index 0000000000..7d531d1461
--- /dev/null
+++ b/spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java
@@ -0,0 +1,66 @@
+package com.baeldung.repository;
+
+import com.baeldung.domain.Article;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+@RunWith(SpringRunner.class)
+@DataJpaTest
+public class ArticleRepositoryIntegrationTest {
+
+ @Autowired
+ private ArticleRepository repository;
+
+ @Test
+ public void givenImportedArticlesWhenFindAllByPublicationDateThenArticles1And2Returned()
+ throws Exception {
+ List result = repository.findAllByPublicationDate(
+ new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-01")
+ );
+
+ assertEquals(2, result.size());
+ assertTrue(result.stream()
+ .map(Article::getId)
+ .allMatch(id -> Arrays.asList(1, 2).contains(id))
+ );
+ }
+
+ @Test
+ public void givenImportedArticlesWhenFindAllByPublicationTimeBetweenThenArticles2And3Returned()
+ throws Exception {
+ List result = repository.findAllByPublicationTimeBetween(
+ new SimpleDateFormat("HH:mm").parse("15:15"),
+ new SimpleDateFormat("HH:mm").parse("16:30")
+ );
+
+ assertEquals(2, result.size());
+ assertTrue(result.stream()
+ .map(Article::getId)
+ .allMatch(id -> Arrays.asList(2, 3).contains(id))
+ );
+ }
+
+ @Test
+ public void givenImportedArticlesWhenFindAllWithCreationDateTimeBeforeThenArticles2And3Returned() throws Exception {
+ List result = repository.findAllWithCreationDateTimeBefore(
+ new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-12-15 10:00")
+ );
+
+ assertEquals(2, result.size());
+ assertTrue(result.stream()
+ .map(Article::getId)
+ .allMatch(id -> Arrays.asList(2, 3).contains(id))
+ );
+ }
+
+}
diff --git a/spring-boot-persistence/src/test/resources/application.properties b/spring-boot-persistence/src/test/resources/application.properties
index a5c1d983cf..a5d09db840 100644
--- a/spring-boot-persistence/src/test/resources/application.properties
+++ b/spring-boot-persistence/src/test/resources/application.properties
@@ -13,4 +13,4 @@ hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
spring.jpa.properties.hibernate.hbm2ddl.import_files=migrated_users.sql
-spring.datasource.data=import_*_users.sql
\ No newline at end of file
+spring.datasource.data=import_*_users.sql,import_articles.sql
\ No newline at end of file
diff --git a/spring-boot-persistence/src/test/resources/import_articles.sql b/spring-boot-persistence/src/test/resources/import_articles.sql
new file mode 100644
index 0000000000..4fe18bf4aa
--- /dev/null
+++ b/spring-boot-persistence/src/test/resources/import_articles.sql
@@ -0,0 +1,3 @@
+insert into Article(id, publication_date, publication_time, creation_date_time) values(1, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:00', 'HH24:MI'), TO_DATE('31/12/2017 07:30', 'DD/MM/YYYY HH24:MI'));
+insert into Article(id, publication_date, publication_time, creation_date_time) values(2, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:30', 'HH24:MI'), TO_DATE('15/12/2017 08:00', 'DD/MM/YYYY HH24:MI'));
+insert into Article(id, publication_date, publication_time, creation_date_time) values(3, TO_DATE('15/12/2017', 'DD/MM/YYYY'), TO_DATE('16:00', 'HH24:MI'), TO_DATE('01/12/2017 13:45', 'DD/MM/YYYY HH24:MI'));
\ No newline at end of file
diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml
index 167a194107..12f51eec94 100644
--- a/spring-boot-security/pom.xml
+++ b/spring-boot-security/pom.xml
@@ -55,6 +55,11 @@
spring-security-test
test
+
+ org.springframework.security
+ spring-security-test
+ test
+
diff --git a/spring-cloud/spring-cloud-bootstrap/README.MD b/spring-cloud/spring-cloud-bootstrap/README.MD
index 164219c185..5185200469 100644
--- a/spring-cloud/spring-cloud-bootstrap/README.MD
+++ b/spring-cloud/spring-cloud-bootstrap/README.MD
@@ -11,5 +11,5 @@
- git add .
- git commit -m "First commit"
- start the config server
- - start the discover server
+ - start the discovery server
- start all the other servers in any order (gateway, svc-book, svc-rating, zipkin)
diff --git a/spring-data-5-reactive/pom.xml b/spring-data-5-reactive/pom.xml
index b2a317878f..bcf37f1da4 100644
--- a/spring-data-5-reactive/pom.xml
+++ b/spring-data-5-reactive/pom.xml
@@ -6,8 +6,6 @@
spring-5-data-reactive
0.0.1-SNAPSHOT
jar
- Spring-5-data-reactive
- Spring-5-data-reactive with Springboot 2.0.1
org.springframework.boot
diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml
index f8cd630ea1..a756ef0497 100644
--- a/spring-data-rest/pom.xml
+++ b/spring-data-rest/pom.xml
@@ -6,7 +6,7 @@
spring-data-rest
1.0
jar
- intro-spring-data-rest
+ spring-data-rest
Intro to Spring Data REST
diff --git a/spring-data-rest/src/test/java/com/baeldung/relationships/SpringDataRelationshipsIntegrationTest.java b/spring-data-rest/src/test/java/com/baeldung/relationships/SpringDataRelationshipsIntegrationTest.java
deleted file mode 100644
index 196dc18d9e..0000000000
--- a/spring-data-rest/src/test/java/com/baeldung/relationships/SpringDataRelationshipsIntegrationTest.java
+++ /dev/null
@@ -1,107 +0,0 @@
-package com.baeldung.relationships;
-
-import static org.junit.Assert.assertEquals;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
-import org.springframework.boot.test.web.client.TestRestTemplate;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.ResponseEntity;
-import org.springframework.test.context.junit4.SpringRunner;
-
-import com.baeldung.SpringDataRestApplication;
-import com.baeldung.models.Address;
-import com.baeldung.models.Author;
-import com.baeldung.models.Book;
-import com.baeldung.models.Library;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(classes = SpringDataRestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
-public class SpringDataRelationshipsIntegrationTest {
-
- @Autowired
- private TestRestTemplate template;
-
- @Value("${local.server.port}")
- private int port;
-
- private static final String BOOK_ENDPOINT = "http://localhost:%s/books/";
- private static final String AUTHOR_ENDPOINT = "http://localhost:%s/authors/";
- private static final String ADDRESS_ENDPOINT = "http://localhost:%s/addresses/";
- private static final String LIBRARY_ENDPOINT = "http://localhost:%s/libraries/";
-
- private static final String LIBRARY_NAME = "My Library";
- private static final String AUTHOR_NAME = "George Orwell";
-
- @Test
- public void whenSaveOneToOneRelationship_thenCorrect() throws JSONException {
- Library library = new Library(LIBRARY_NAME);
- template.postForEntity(String.format(LIBRARY_ENDPOINT, port), library, Library.class);
-
- Address address = new Address("Main street, nr 1");
- template.postForEntity(String.format(ADDRESS_ENDPOINT, port), address, Address.class);
-
- HttpHeaders requestHeaders = new HttpHeaders();
- requestHeaders.add("Content-type", "text/uri-list");
- HttpEntity httpEntity = new HttpEntity<>(String.format(ADDRESS_ENDPOINT, port) + "/1", requestHeaders);
- template.exchange(String.format(LIBRARY_ENDPOINT, port) + "/1/libraryAddress", HttpMethod.PUT, httpEntity, String.class);
-
- ResponseEntity libraryGetResponse = template.getForEntity(String.format(ADDRESS_ENDPOINT, port) + "/1/library", Library.class);
- assertEquals("library is incorrect", libraryGetResponse.getBody()
- .getName(), LIBRARY_NAME);
- }
-
- @Test
- public void whenSaveOneToManyRelationship_thenCorrect() throws JSONException{
- Library library = new Library(LIBRARY_NAME);
- template.postForEntity(String.format(LIBRARY_ENDPOINT, port), library, Library.class);
-
- Book book1 = new Book("Dune");
- template.postForEntity(String.format(BOOK_ENDPOINT, port), book1, Book.class);
-
- Book book2 = new Book("1984");
- template.postForEntity(String.format(BOOK_ENDPOINT, port), book2, Book.class);
-
- HttpHeaders requestHeaders = new HttpHeaders();
- requestHeaders.add("Content-type", "text/uri-list");
- HttpEntity bookHttpEntity = new HttpEntity<>(String.format(LIBRARY_ENDPOINT, port) + "/1", requestHeaders);
- template.exchange(String.format(BOOK_ENDPOINT, port) + "/1/library", HttpMethod.PUT, bookHttpEntity, String.class);
- template.exchange(String.format(BOOK_ENDPOINT, port) + "/2/library", HttpMethod.PUT, bookHttpEntity, String.class);
-
- ResponseEntity libraryGetResponse = template.getForEntity(String.format(BOOK_ENDPOINT, port) + "/1/library", Library.class);
- assertEquals("library is incorrect", libraryGetResponse.getBody()
- .getName(), LIBRARY_NAME);
- }
-
- @Test
- public void whenSaveManyToManyRelationship_thenCorrect() throws JSONException{
- Author author1 = new Author(AUTHOR_NAME);
- template.postForEntity(String.format(AUTHOR_ENDPOINT, port), author1, Author.class);
-
- Book book1 = new Book("Animal Farm");
- template.postForEntity(String.format(BOOK_ENDPOINT, port), book1, Book.class);
-
- Book book2 = new Book("1984");
- template.postForEntity(String.format(BOOK_ENDPOINT, port), book2, Book.class);
-
- HttpHeaders requestHeaders = new HttpHeaders();
- requestHeaders.add("Content-type", "text/uri-list");
- HttpEntity httpEntity = new HttpEntity<>(String.format(BOOK_ENDPOINT, port) + "/1\n" + String.format(BOOK_ENDPOINT, port) + "/2", requestHeaders);
- template.exchange(String.format(AUTHOR_ENDPOINT, port) + "/1/books", HttpMethod.PUT, httpEntity, String.class);
-
- String jsonResponse = template.getForObject(String.format(BOOK_ENDPOINT, port) + "/1/authors", String.class);
- JSONObject jsonObj = new JSONObject(jsonResponse).getJSONObject("_embedded");
- JSONArray jsonArray = jsonObj.getJSONArray("authors");
- assertEquals("author is incorrect", jsonArray.getJSONObject(0)
- .getString("name"), AUTHOR_NAME);
- }
-}
diff --git a/spring-hibernate4/pom.xml b/spring-hibernate4/pom.xml
index 08533350d2..505a218a94 100644
--- a/spring-hibernate4/pom.xml
+++ b/spring-hibernate4/pom.xml
@@ -127,6 +127,12 @@
${hsqldb.version}
test
+
+ com.h2database
+ h2
+ ${h2.version}
+ test
+
@@ -153,6 +159,7 @@
8.5.8
1.1
2.3.4
+ 1.4.193
5.3.3.Final
diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java
index 2559d5f048..9fda4c43bb 100644
--- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java
+++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java
@@ -16,7 +16,7 @@ public class UserEager implements Serializable {
@Column(name = "USER_ID")
private Long userId;
- @OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
+ @OneToMany(fetch = FetchType.EAGER)
private Set orderDetail = new HashSet();
public UserEager() {
diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java
index 5852e74418..a78eaa4ac0 100644
--- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java
+++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java
@@ -16,7 +16,7 @@ public class UserLazy implements Serializable {
@Column(name = "USER_ID")
private Long userId;
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
+ @OneToMany(fetch = FetchType.LAZY)
private Set orderDetail = new HashSet();
public UserLazy() {
diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java
index 1a5142c5c2..35cdd254e3 100644
--- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java
+++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java
@@ -20,7 +20,7 @@ public class FetchingAppView {
public Set lazyLoaded() {
final Session sessionLazy = HibernateUtil.getHibernateSession("lazy");
List users = sessionLazy.createQuery("From UserLazy").list();
- UserLazy userLazyLoaded = users.get(3);
+ UserLazy userLazyLoaded = users.get(0);
// since data is lazyloaded so data won't be initialized
return (userLazyLoaded.getOrderDetail());
}
@@ -31,7 +31,7 @@ public class FetchingAppView {
// data should be loaded in the following line
// also note the queries generated
List user = sessionEager.createQuery("From UserEager").list();
- UserEager userEagerLoaded = user.get(3);
+ UserEager userEagerLoaded = user.get(0);
return userEagerLoaded.getOrderDetail();
}
diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java
index ed2e111c8f..2f23a9a532 100644
--- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java
+++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java
@@ -5,11 +5,6 @@ import static org.junit.Assert.assertNotNull;
import java.util.List;
-import com.baeldung.persistence.model.Foo;
-import com.baeldung.persistence.service.IBarAuditableService;
-import com.baeldung.persistence.service.IFooAuditableService;
-import com.baeldung.spring.PersistenceConfig;
-import com.baeldung.persistence.model.Bar;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
@@ -26,8 +21,14 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
+import com.baeldung.persistence.model.Bar;
+import com.baeldung.persistence.model.Foo;
+import com.baeldung.persistence.service.IBarAuditableService;
+import com.baeldung.persistence.service.IFooAuditableService;
+import com.baeldung.spring.config.PersistenceTestConfig;
+
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class EnversFooBarAuditIntegrationTest {
private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class);
diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java
index b63a4b989b..733074a6a3 100644
--- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java
+++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java
@@ -7,10 +7,6 @@ import static org.junit.Assert.assertTrue;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
-import com.baeldung.persistence.model.Bar;
-import com.baeldung.persistence.model.Bar.OPERATION;
-import com.baeldung.persistence.service.IBarService;
-import com.baeldung.spring.PersistenceConfig;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -25,8 +21,13 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
+import com.baeldung.persistence.model.Bar;
+import com.baeldung.persistence.model.Bar.OPERATION;
+import com.baeldung.persistence.service.IBarService;
+import com.baeldung.spring.config.PersistenceTestConfig;
+
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class JPABarAuditIntegrationTest {
private static Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class);
diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java
index e794b282f6..18227abd28 100644
--- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java
+++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java
@@ -6,9 +6,6 @@ import static org.junit.Assert.assertTrue;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
-import com.baeldung.persistence.model.Bar;
-import com.baeldung.persistence.service.IBarService;
-import com.baeldung.spring.PersistenceConfig;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -24,8 +21,12 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
+import com.baeldung.persistence.model.Bar;
+import com.baeldung.persistence.service.IBarService;
+import com.baeldung.spring.config.PersistenceTestConfig;
+
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class SpringDataJPABarAuditIntegrationTest {
private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class);
diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java
index 721b20db68..fd7bc4aabf 100644
--- a/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java
+++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java
@@ -7,9 +7,6 @@ import static org.junit.Assert.assertThat;
import java.util.List;
-import com.baeldung.persistence.model.Foo;
-import com.baeldung.persistence.service.IFooService;
-import com.baeldung.spring.PersistenceConfig;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
@@ -26,10 +23,13 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
+import com.baeldung.persistence.model.Foo;
+import com.baeldung.persistence.service.IFooService;
+import com.baeldung.spring.config.PersistenceTestConfig;
import com.google.common.collect.Lists;
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class FooPaginationPersistenceIntegrationTest {
@Autowired
diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java
index 0f76526960..8173088af0 100644
--- a/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java
+++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java
@@ -5,9 +5,6 @@ import static org.junit.Assert.assertNull;
import java.util.List;
import java.util.Set;
-import com.baeldung.persistence.model.Bar;
-import com.baeldung.persistence.model.Foo;
-import com.baeldung.spring.PersistenceConfig;
import org.hibernate.Criteria;
import org.hibernate.NullPrecedence;
import org.hibernate.Query;
@@ -23,8 +20,12 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
+import com.baeldung.persistence.model.Bar;
+import com.baeldung.persistence.model.Foo;
+import com.baeldung.spring.config.PersistenceTestConfig;
+
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
@SuppressWarnings("unchecked")
public class FooSortingPersistenceIntegrationTest {
diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java
index c77f5dfb95..146f8e9622 100644
--- a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java
+++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java
@@ -2,8 +2,6 @@ package com.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import com.baeldung.persistence.model.Foo;
-import com.baeldung.spring.PersistenceConfig;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
@@ -15,8 +13,11 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
+import com.baeldung.persistence.model.Foo;
+import com.baeldung.spring.config.PersistenceTestConfig;
+
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class FooServiceBasicPersistenceIntegrationTest {
@Autowired
diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java
index b82d4621ab..6d426849a6 100644
--- a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java
+++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java
@@ -2,8 +2,6 @@ package com.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import com.baeldung.persistence.model.Foo;
-import com.baeldung.spring.PersistenceConfig;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -16,8 +14,11 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
+import com.baeldung.persistence.model.Foo;
+import com.baeldung.spring.config.PersistenceTestConfig;
+
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class FooServicePersistenceIntegrationTest {
@Autowired
diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java
similarity index 95%
rename from spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java
rename to spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java
index db64107405..9ec04d297c 100644
--- a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java
+++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java
@@ -26,9 +26,9 @@ import com.baeldung.spring.PersistenceConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class FooStoredProceduresIntegrationTest {
+public class FooStoredProceduresLiveTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresIntegrationTest.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresLiveTest.class);
@Autowired
private SessionFactory sessionFactory;
diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java
index 9e8c4aba92..5a73e39ca2 100644
--- a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java
+++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java
@@ -1,8 +1,5 @@
package com.baeldung.persistence.service;
-import com.baeldung.persistence.model.Child;
-import com.baeldung.persistence.model.Parent;
-import com.baeldung.spring.PersistenceConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@@ -11,8 +8,12 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
+import com.baeldung.persistence.model.Child;
+import com.baeldung.persistence.model.Parent;
+import com.baeldung.spring.config.PersistenceTestConfig;
+
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class ParentServicePersistenceIntegrationTest {
@Autowired
diff --git a/spring-hibernate4/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java b/spring-hibernate4/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java
new file mode 100644
index 0000000000..9bf55c902a
--- /dev/null
+++ b/spring-hibernate4/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java
@@ -0,0 +1,179 @@
+package com.baeldung.spring.config;
+
+import java.util.Properties;
+
+import javax.sql.DataSource;
+
+import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
+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.dao.annotation.PersistenceExceptionTranslationPostProcessor;
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.orm.hibernate4.HibernateTransactionManager;
+import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
+import org.springframework.orm.jpa.JpaTransactionManager;
+import org.springframework.orm.jpa.JpaVendorAdapter;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import com.baeldung.persistence.dao.IBarAuditableDao;
+import com.baeldung.persistence.dao.IBarDao;
+import com.baeldung.persistence.dao.IFooAuditableDao;
+import com.baeldung.persistence.dao.IFooDao;
+import com.baeldung.persistence.dao.impl.BarAuditableDao;
+import com.baeldung.persistence.dao.impl.BarDao;
+import com.baeldung.persistence.dao.impl.BarJpaDao;
+import com.baeldung.persistence.dao.impl.FooAuditableDao;
+import com.baeldung.persistence.dao.impl.FooDao;
+import com.baeldung.persistence.service.IBarAuditableService;
+import com.baeldung.persistence.service.IBarService;
+import com.baeldung.persistence.service.IFooAuditableService;
+import com.baeldung.persistence.service.IFooService;
+import com.baeldung.persistence.service.impl.BarAuditableService;
+import com.baeldung.persistence.service.impl.BarJpaService;
+import com.baeldung.persistence.service.impl.BarSpringDataJpaService;
+import com.baeldung.persistence.service.impl.FooAuditableService;
+import com.baeldung.persistence.service.impl.FooService;
+import com.google.common.base.Preconditions;
+
+@Configuration
+@EnableTransactionManagement
+@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager")
+@EnableJpaAuditing
+@PropertySource({ "classpath:persistence-h2.properties" })
+@ComponentScan({ "com.baeldung.persistence" })
+public class PersistenceTestConfig {
+
+ @Autowired
+ private Environment env;
+
+ public PersistenceTestConfig() {
+ super();
+ }
+
+ @Bean
+ public LocalSessionFactoryBean sessionFactory() {
+ final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
+ sessionFactory.setDataSource(restDataSource());
+ sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
+ sessionFactory.setHibernateProperties(hibernateProperties());
+
+ return sessionFactory;
+ }
+
+ @Bean
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
+ final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
+ emf.setDataSource(restDataSource());
+ emf.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
+
+ final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
+ emf.setJpaVendorAdapter(vendorAdapter);
+ emf.setJpaProperties(hibernateProperties());
+
+ return emf;
+ }
+
+ @Bean
+ public DataSource restDataSource() {
+ final BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
+ dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
+ dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
+ dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
+
+ return dataSource;
+ }
+
+ @Bean
+ public PlatformTransactionManager hibernateTransactionManager() {
+ final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
+ transactionManager.setSessionFactory(sessionFactory().getObject());
+ return transactionManager;
+ }
+
+ @Bean
+ public PlatformTransactionManager jpaTransactionManager() {
+ final JpaTransactionManager transactionManager = new JpaTransactionManager();
+ transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
+ return transactionManager;
+ }
+
+ @Bean
+ public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
+ return new PersistenceExceptionTranslationPostProcessor();
+ }
+
+ @Bean
+ public IBarService barJpaService() {
+ return new BarJpaService();
+ }
+
+ @Bean
+ public IBarService barSpringDataJpaService() {
+ return new BarSpringDataJpaService();
+ }
+
+ @Bean
+ public IFooService fooHibernateService() {
+ return new FooService();
+ }
+
+ @Bean
+ public IBarAuditableService barHibernateAuditableService() {
+ return new BarAuditableService();
+ }
+
+ @Bean
+ public IFooAuditableService fooHibernateAuditableService() {
+ return new FooAuditableService();
+ }
+
+ @Bean
+ public IBarDao barJpaDao() {
+ return new BarJpaDao();
+ }
+
+ @Bean
+ public IBarDao barHibernateDao() {
+ return new BarDao();
+ }
+
+ @Bean
+ public IBarAuditableDao barHibernateAuditableDao() {
+ return new BarAuditableDao();
+ }
+
+ @Bean
+ public IFooDao fooHibernateDao() {
+ return new FooDao();
+ }
+
+ @Bean
+ public IFooAuditableDao fooHibernateAuditableDao() {
+ return new FooAuditableDao();
+ }
+
+ private final Properties hibernateProperties() {
+ final Properties hibernateProperties = new Properties();
+ hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
+ hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
+
+ hibernateProperties.setProperty("hibernate.show_sql", "true");
+ // hibernateProperties.setProperty("hibernate.format_sql", "true");
+ // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
+
+ // Envers properties
+ hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
+
+ return hibernateProperties;
+ }
+
+}
\ No newline at end of file
diff --git a/spring-hibernate4/src/test/resources/criteria.cfg.xml b/spring-hibernate4/src/test/resources/criteria.cfg.xml
index 653b5a188a..726e9acb3f 100644
--- a/spring-hibernate4/src/test/resources/criteria.cfg.xml
+++ b/spring-hibernate4/src/test/resources/criteria.cfg.xml
@@ -5,11 +5,12 @@
- com.mysql.jdbc.Driver
- jdbc:mysql://localhost:3306/test
- root
- iamtheking
- org.hibernate.dialect.MySQLDialect
+ org.h2.Driver
+ jdbc:h2:mem:testdb
+ sa
+
+ org.hibernate.dialect.H2Dialect
+ update
true
diff --git a/spring-hibernate4/src/test/resources/fetching.cfg.xml b/spring-hibernate4/src/test/resources/fetching.cfg.xml
index acee7008ba..55a3aeb51c 100644
--- a/spring-hibernate4/src/test/resources/fetching.cfg.xml
+++ b/spring-hibernate4/src/test/resources/fetching.cfg.xml
@@ -5,14 +5,15 @@
- com.mysql.jdbc.Driver
- jdbc:mysql://localhost:3306/test
- root
- iamtheking
- org.hibernate.dialect.MySQLDialect
+ org.h2.Driver
+ jdbc:h2:mem:testdb
+ sa
+
+ org.hibernate.dialect.H2Dialect
+ update
true
-
+
\ No newline at end of file
diff --git a/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml
index 1dc37d0cf8..8fcf578660 100644
--- a/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml
+++ b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml
@@ -5,14 +5,15 @@
- com.mysql.jdbc.Driver
- jdbc:mysql://localhost:3306/test
- root
- iamtheking
- org.hibernate.dialect.MySQLDialect
+ org.h2.Driver
+ jdbc:h2:mem:testdb
+ sa
+
+ org.hibernate.dialect.H2Dialect
+ update
true
-
+
\ No newline at end of file
diff --git a/spring-hibernate4/src/test/resources/persistence-h2.properties b/spring-hibernate4/src/test/resources/persistence-h2.properties
new file mode 100644
index 0000000000..911619193b
--- /dev/null
+++ b/spring-hibernate4/src/test/resources/persistence-h2.properties
@@ -0,0 +1,13 @@
+# jdbc.X
+jdbc.driverClassName=org.h2.Driver
+jdbc.url=jdbc:h2:mem:test
+jdbc.user=sa
+jdbc.pass=
+
+# hibernate.X
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.show_sql=false
+hibernate.hbm2ddl.auto=create-drop
+
+# envers.X
+envers.audit_table_suffix=_audit_log
diff --git a/spring-reactive-kotlin/pom.xml b/spring-reactive-kotlin/pom.xml
new file mode 100644
index 0000000000..1425adc191
--- /dev/null
+++ b/spring-reactive-kotlin/pom.xml
@@ -0,0 +1,93 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ springreactivekotlin
+ 0.0.1-SNAPSHOT
+ jar
+
+ springreactivekotlin
+ Demo project for Spring Boot
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.0.3.RELEASE
+
+
+
+
+ UTF-8
+ UTF-8
+ 1.8
+ 1.2.41
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-webflux
+
+
+ com.fasterxml.jackson.module
+ jackson-module-kotlin
+
+
+ org.jetbrains.kotlin
+ kotlin-stdlib-jdk8
+
+
+ org.jetbrains.kotlin
+ kotlin-reflect
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ io.projectreactor
+ reactor-test
+ test
+
+
+
+
+ ${project.basedir}/src/main/kotlin
+ ${project.basedir}/src/test/kotlin
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+ kotlin-maven-plugin
+ org.jetbrains.kotlin
+
+
+ -Xjsr305=strict
+
+
+ spring
+
+
+
+
+ org.jetbrains.kotlin
+ kotlin-maven-allopen
+ ${kotlin.version}
+
+
+
+
+
+
+
+
diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Application.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Application.kt
new file mode 100644
index 0000000000..87ac7417b7
--- /dev/null
+++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Application.kt
@@ -0,0 +1,11 @@
+package com.baeldung.springreactivekotlin
+
+import org.springframework.boot.SpringApplication
+import org.springframework.boot.autoconfigure.SpringBootApplication
+
+@SpringBootApplication
+class Application
+
+fun main(args: Array) {
+ SpringApplication.run(Application::class.java, *args)
+}
diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Controller.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Controller.kt
new file mode 100644
index 0000000000..76f8a62b85
--- /dev/null
+++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Controller.kt
@@ -0,0 +1,18 @@
+package com.baeldung.springreactivekotlin
+
+import org.springframework.http.MediaType
+import org.springframework.stereotype.Controller
+import org.springframework.web.bind.annotation.GetMapping
+import org.springframework.web.bind.annotation.ResponseBody
+import reactor.core.publisher.Flux
+
+@Controller
+class Controller {
+
+ @GetMapping(path = ["/numbers"], produces = [MediaType.APPLICATION_STREAM_JSON_VALUE])
+ @ResponseBody
+ fun getNumbers(): Flux {
+ return Flux.range(1, 100)
+ }
+
+}
diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Device.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Device.kt
new file mode 100644
index 0000000000..9eb6eb8488
--- /dev/null
+++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Device.kt
@@ -0,0 +1,5 @@
+package com.baeldung.springreactivekotlin
+
+class Device(val name: String, val reading: Double) {
+
+}
diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsHandler.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsHandler.kt
new file mode 100644
index 0000000000..0ef9f37f1b
--- /dev/null
+++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsHandler.kt
@@ -0,0 +1,36 @@
+package com.baeldung.springreactivekotlin
+
+import org.springframework.stereotype.Component
+import org.springframework.web.reactive.function.BodyInserters.fromObject
+import org.springframework.web.reactive.function.server.ServerRequest
+import org.springframework.web.reactive.function.server.ServerResponse
+import reactor.core.publisher.Mono
+
+@Component
+class HomeSensorsHandler {
+
+ var data = mapOf("lamp" to arrayOf(0.7, 0.65, 0.67), "fridge" to arrayOf(12.0, 11.9, 12.5))
+
+ fun setLight(request: ServerRequest): Mono = ServerResponse.ok().build()
+
+ fun getLightReading(request: ServerRequest): Mono =
+ ServerResponse.ok().body(fromObject(data["lamp"]!!))
+
+ fun getDeviceReadings(request: ServerRequest): Mono {
+ val id = request.pathVariable("id")
+ return ServerResponse.ok().body(fromObject(Device(id, 1.0)))
+ }
+
+ fun getAllDevices(request: ServerRequest): Mono =
+ ServerResponse.ok().body(fromObject(arrayOf("lamp", "tv")))
+
+ fun getAllDeviceApi(request: ServerRequest): Mono =
+ ServerResponse.ok().body(fromObject(arrayListOf("kettle", "fridge")))
+
+ fun setDeviceReadingApi(request: ServerRequest): Mono {
+ return request.bodyToMono(Device::class.java).flatMap { it ->
+ ServerResponse.ok().body(fromObject(Device(it.name.toUpperCase(), it.reading)))
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsRouters.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsRouters.kt
new file mode 100644
index 0000000000..27d87afd89
--- /dev/null
+++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsRouters.kt
@@ -0,0 +1,32 @@
+package com.baeldung.springreactivekotlin
+
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.http.MediaType.APPLICATION_JSON
+import org.springframework.http.MediaType.TEXT_HTML
+import org.springframework.web.reactive.function.server.router
+
+@Configuration
+class HomeSensorsRouters(private val handler: HomeSensorsHandler) {
+
+ @Bean
+ fun roomsRouter() = router {
+ (accept(TEXT_HTML) and "/room").nest {
+ GET("/light", handler::getLightReading)
+ POST("/light", handler::setLight)
+ }
+ }
+
+ @Bean
+ fun deviceRouter() = router {
+ accept(TEXT_HTML).nest {
+ (GET("/device/") or GET("/devices/")).invoke(handler::getAllDevices)
+ GET("/device/{id}", handler::getDeviceReadings)
+ }
+ (accept(APPLICATION_JSON) and "/api").nest {
+ (GET("/device/") or GET("/devices/")).invoke(handler::getAllDeviceApi)
+ POST("/device/", handler::setDeviceReadingApi)
+ }
+ }
+
+}
diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Routes.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Routes.kt
new file mode 100644
index 0000000000..9015fc5df8
--- /dev/null
+++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Routes.kt
@@ -0,0 +1,16 @@
+package com.baeldung.springreactivekotlin
+
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.web.reactive.function.server.ServerResponse
+import org.springframework.web.reactive.function.server.router
+
+import org.springframework.web.reactive.function.BodyInserters.fromObject
+
+@Configuration
+class SimpleRoute {
+ @Bean
+ fun route() = router {
+ GET("/route") { _ -> ServerResponse.ok().body(fromObject(arrayOf(1, 2, 3))) }
+ }
+}
\ No newline at end of file
diff --git a/spring-reactive-kotlin/src/test/kotlin/RoutesTest.kt b/spring-reactive-kotlin/src/test/kotlin/RoutesTest.kt
new file mode 100644
index 0000000000..ba640070e3
--- /dev/null
+++ b/spring-reactive-kotlin/src/test/kotlin/RoutesTest.kt
@@ -0,0 +1,35 @@
+package veontomo
+
+import com.baeldung.springreactivekotlin.SimpleRoute
+import org.junit.Before
+import org.junit.Test
+import org.springframework.test.web.reactive.server.WebTestClient
+
+class RoutesTest {
+
+ lateinit var client: WebTestClient
+
+ @Before
+ fun init() {
+ this.client = WebTestClient.bindToRouterFunction(SimpleRoute().route()).build()
+ }
+
+
+ @Test
+ fun whenRequestToRoute_thenStatusShouldBeOk() {
+ client.get()
+ .uri("/route")
+ .exchange()
+ .expectStatus().isOk
+ }
+
+
+ @Test
+ fun whenRequestToRoute_thenBodyShouldContainArray123() {
+ client.get()
+ .uri("/route")
+ .exchange()
+ .expectBody()
+ .json("[1, 2, 3]")
+ }
+}
\ No newline at end of file
diff --git a/spring-rest-hal-browser/pom.xml b/spring-rest-hal-browser/pom.xml
new file mode 100644
index 0000000000..6c56faf0b2
--- /dev/null
+++ b/spring-rest-hal-browser/pom.xml
@@ -0,0 +1,53 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ spring-rest-hal-browser
+ 1.0-SNAPSHOT
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ 1.8
+ 1.8
+
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+ 2.0.3.RELEASE
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+ 2.0.3.RELEASE
+
+
+
+ org.springframework.data
+ spring-data-rest-hal-browser
+ 3.0.8.RELEASE
+
+
+
+ com.h2database
+ h2
+ 1.4.197
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-rest-hal-browser/src/main/java/com/baeldung/App.java b/spring-rest-hal-browser/src/main/java/com/baeldung/App.java
new file mode 100644
index 0000000000..14b6c201d5
--- /dev/null
+++ b/spring-rest-hal-browser/src/main/java/com/baeldung/App.java
@@ -0,0 +1,13 @@
+package com.baeldung;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class App {
+
+ public static void main(String[] args) {
+ SpringApplication.run(App.class);
+ }
+
+}
diff --git a/spring-rest-hal-browser/src/main/java/com/baeldung/config/DBLoader.java b/spring-rest-hal-browser/src/main/java/com/baeldung/config/DBLoader.java
new file mode 100644
index 0000000000..7251ef0e8c
--- /dev/null
+++ b/spring-rest-hal-browser/src/main/java/com/baeldung/config/DBLoader.java
@@ -0,0 +1,108 @@
+package com.baeldung.config;
+
+import com.baeldung.data.BookRepository;
+import com.baeldung.model.Book;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.ApplicationArguments;
+import org.springframework.boot.ApplicationRunner;
+import org.springframework.stereotype.Component;
+
+import java.util.Random;
+import java.util.stream.IntStream;
+
+@Component
+public class DBLoader implements ApplicationRunner {
+
+ private final BookRepository bookRepository;
+
+ @Autowired
+ DBLoader(BookRepository bookRepository){
+ this.bookRepository = bookRepository;
+ }
+
+
+ public void run(ApplicationArguments applicationArguments) throws Exception {
+
+ String[] templates = {
+ "Up and running with %s",
+ "%s Basics",
+ "%s for Beginners",
+ "%s for Neckbeards",
+ "Under the hood: %s",
+ "Discovering %s",
+ "A short guide to %s",
+ "%s with Baeldung"
+ };
+
+ String[] buzzWords = {
+ "Spring REST Data",
+ "Java 9",
+ "Scala",
+ "Groovy",
+ "Hibernate",
+ "Spring HATEOS",
+ "The HAL Browser",
+ "Spring webflux",
+ };
+
+ String[] authorFirstName = {
+ "John %s",
+ "Steve %s",
+ "Samantha %s",
+ "Gale %s",
+ "Tom %s"
+ };
+
+ String[] authorLastName = {
+ "Giles",
+ "Gill",
+ "Smith",
+ "Armstrong"
+ };
+
+ String[] blurbs = {
+ "It was getting dark when the %s %s" ,
+ "Scott was nearly there when he heard that a %s %s",
+ "Diana was a lovable Java coder until the %s %s",
+ "The gripping story of a small %s and the day it %s"
+ };
+
+ String[] blublMiddles = {
+ "distaster",
+ "dog",
+ "cat",
+ "turtle",
+ "hurricane"
+ };
+
+ String[] end = {
+ "hit the school",
+ "memorised pi to 100 decimal places!",
+ "became a world champion armwrestler",
+ "became a Java REST master!!"
+ };
+
+ Random random = new Random();
+
+ IntStream.range(0, 100)
+ .forEach(i -> {
+ String template = templates[i % templates.length];
+ String buzzword = buzzWords[i % buzzWords.length];
+ String blurbStart = blurbs[i % blurbs.length];
+ String middle = blublMiddles[i % blublMiddles.length];
+ String ending = end[i % end.length];
+ String blurb = String.format(blurbStart, middle, ending);
+ String firstName = authorFirstName[i % authorFirstName.length];
+ String lastname = authorLastName[i % authorLastName.length];
+ Book book = new Book(String.format(template, buzzword), String.format(firstName, lastname), blurb, random.nextInt(1000-200) + 200);
+
+ bookRepository.save(book);
+
+ System.out.println(book);
+
+ });
+
+
+
+ }
+}
diff --git a/spring-rest-hal-browser/src/main/java/com/baeldung/config/RestConfig.java b/spring-rest-hal-browser/src/main/java/com/baeldung/config/RestConfig.java
new file mode 100644
index 0000000000..858371facc
--- /dev/null
+++ b/spring-rest-hal-browser/src/main/java/com/baeldung/config/RestConfig.java
@@ -0,0 +1,23 @@
+package com.baeldung.config;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.data.rest.core.event.ValidatingRepositoryEventListener;
+import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
+import org.springframework.validation.Validator;
+
+@Configuration
+public class RestConfig extends RepositoryRestConfigurerAdapter {
+
+ //access to global validator
+ @Autowired
+ @Lazy
+ private Validator validator;
+
+ @Override
+ public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
+ validatingListener.addValidator("beforeCreate", validator );
+ validatingListener.addValidator("beforeSave", validator);
+ }
+}
diff --git a/spring-rest-hal-browser/src/main/java/com/baeldung/data/BookRepository.java b/spring-rest-hal-browser/src/main/java/com/baeldung/data/BookRepository.java
new file mode 100644
index 0000000000..d8e35974b1
--- /dev/null
+++ b/spring-rest-hal-browser/src/main/java/com/baeldung/data/BookRepository.java
@@ -0,0 +1,21 @@
+package com.baeldung.data;
+
+import com.baeldung.model.Book;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.PagingAndSortingRepository;
+import org.springframework.data.repository.query.Param;
+import org.springframework.data.rest.core.annotation.RestResource;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface BookRepository extends PagingAndSortingRepository {
+
+ @RestResource(rel = "title-contains", path="title-contains")
+ Page findByTitleContaining(@Param("query") String query, Pageable page);
+
+ @RestResource(rel = "author-contains", path="author-contains", exported = false)
+ Page findByAuthorContaining(@Param("query") String query, Pageable page);
+
+}
diff --git a/spring-rest-hal-browser/src/main/java/com/baeldung/model/Book.java b/spring-rest-hal-browser/src/main/java/com/baeldung/model/Book.java
new file mode 100644
index 0000000000..b1dc1b41f3
--- /dev/null
+++ b/spring-rest-hal-browser/src/main/java/com/baeldung/model/Book.java
@@ -0,0 +1,86 @@
+package com.baeldung.model;
+
+import javax.persistence.*;
+import javax.validation.constraints.NotNull;
+
+@Entity
+public class Book {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private long id;
+
+ @NotNull
+ @Column(columnDefinition = "VARCHAR", length = 100)
+ private String title;
+
+ @NotNull
+ @Column(columnDefinition = "VARCHAR", length = 100)
+ private String author;
+
+ @Column(columnDefinition = "VARCHAR", length = 1000)
+ private String blurb;
+
+ private int pages;
+
+ public Book() {
+ }
+
+ public Book(@NotNull String title, @NotNull String author, String blurb, int pages) {
+ this.title = title;
+ this.author = author;
+ this.blurb = blurb;
+ this.pages = pages;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getAuthor() {
+ return author;
+ }
+
+ public void setAuthor(String author) {
+ this.author = author;
+ }
+
+ public String getBlurb() {
+ return blurb;
+ }
+
+ public void setBlurb(String blurb) {
+ this.blurb = blurb;
+ }
+
+ public int getPages() {
+ return pages;
+ }
+
+ public void setPages(int pages) {
+ this.pages = pages;
+ }
+
+ @Override
+ public String toString() {
+ return "Book{" +
+ "id=" + id +
+ ", title='" + title + '\'' +
+ ", author='" + author + '\'' +
+ ", blurb='" + blurb + '\'' +
+ ", pages=" + pages +
+ '}';
+ }
+}
diff --git a/spring-rest-hal-browser/src/main/resources/application.properties b/spring-rest-hal-browser/src/main/resources/application.properties
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/spring-rest-template/.gitignore b/spring-rest-template/.gitignore
new file mode 100644
index 0000000000..afdfaa6ded
--- /dev/null
+++ b/spring-rest-template/.gitignore
@@ -0,0 +1,14 @@
+*.class
+
+#folders#
+/target
+/neoDb*
+/data
+/src/main/webapp/WEB-INF/classes
+*/META-INF/*
+*/.idea/*
+
+# Packaged files #
+*.jar
+*.war
+*.ear
\ No newline at end of file
diff --git a/spring-rest-template/README.md b/spring-rest-template/README.md
new file mode 100644
index 0000000000..bf35f0d32c
--- /dev/null
+++ b/spring-rest-template/README.md
@@ -0,0 +1,4 @@
+## Spring REST Template Example Project
+
+### The Course
+The "REST With Spring" Classes: http://bit.ly/restwithspring
diff --git a/spring-rest-template/checkstyle.xml b/spring-rest-template/checkstyle.xml
new file mode 100644
index 0000000000..85063a7570
--- /dev/null
+++ b/spring-rest-template/checkstyle.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-rest-template/pom.xml b/spring-rest-template/pom.xml
new file mode 100644
index 0000000000..fa93308cf5
--- /dev/null
+++ b/spring-rest-template/pom.xml
@@ -0,0 +1,83 @@
+
+ 4.0.0
+ com.baeldung
+ spring-rest-template
+ 0.1-SNAPSHOT
+ spring-rest-template
+ jar
+
+
+ parent-boot-2
+ com.baeldung
+ 0.0.1-SNAPSHOT
+ ../parent-boot-2
+
+
+
+
+
+
+ org.springframework
+ spring-web
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+
+
+ spring-rest-template
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+ ${checkstyle-maven-plugin.version}
+
+ checkstyle.xml
+
+
+
+
+ check
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+ 3
+ true
+
+ **/*IntegrationTest.java
+ **/*LongRunningUnitTest.java
+ **/*ManualTest.java
+ **/*LiveTest.java
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+ ${checkstyle-maven-plugin.version}
+
+ checkstyle.xml
+
+
+
+
+
+
+
+ 3.0.0
+
+
diff --git a/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java b/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java
new file mode 100644
index 0000000000..804013d4dc
--- /dev/null
+++ b/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java
@@ -0,0 +1,62 @@
+package com.baeldung.web.upload.client;
+
+import org.springframework.core.io.FileSystemResource;
+import org.springframework.core.io.Resource;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.client.RestTemplate;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+public class MultipartFileUploadClient {
+
+ public static void main(String[] args) throws IOException {
+ uploadSingleFile();
+ uploadMultipleFile();
+ }
+
+ private static void uploadSingleFile() throws IOException {
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.MULTIPART_FORM_DATA);
+
+ MultiValueMap body = new LinkedMultiValueMap<>();
+ body.add("file", getTestFile());
+
+
+ HttpEntity> requestEntity = new HttpEntity<>(body, headers);
+ String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/";
+ RestTemplate restTemplate = new RestTemplate();
+ ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
+ System.out.println("Response code: " + response.getStatusCode());
+ }
+
+ private static void uploadMultipleFile() throws IOException {
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.MULTIPART_FORM_DATA);
+
+ MultiValueMap body = new LinkedMultiValueMap<>();
+ body.add("files", getTestFile());
+ body.add("files", getTestFile());
+ body.add("files", getTestFile());
+
+ HttpEntity> requestEntity = new HttpEntity<>(body, headers);
+ String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/";
+ RestTemplate restTemplate = new RestTemplate();
+ ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
+ System.out.println("Response code: " + response.getStatusCode());
+ }
+
+ public static Resource getTestFile() throws IOException {
+ Path testFile = Files.createTempFile("test-file", ".txt");
+ System.out.println("Creating and Uploading Test File: " + testFile);
+ Files.write(testFile, "Hello World !!, This is a test file.".getBytes());
+ return new FileSystemResource(testFile.toFile());
+ }
+
+}
diff --git a/spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java b/spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java
new file mode 100644
index 0000000000..d6821196eb
--- /dev/null
+++ b/spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java
@@ -0,0 +1,17 @@
+package com.baeldung.web.upload.app;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
+import org.springframework.context.annotation.ComponentScan;
+
+@EnableAutoConfiguration
+@ComponentScan("com.baeldung.web.upload")
+@SpringBootApplication
+public class Application extends SpringBootServletInitializer {
+
+ public static void main(final String[] args) {
+ SpringApplication.run(Application.class, args);
+ }
+}
\ No newline at end of file
diff --git a/spring-rest/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java b/spring-rest/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java
new file mode 100644
index 0000000000..547aec17a0
--- /dev/null
+++ b/spring-rest/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java
@@ -0,0 +1,61 @@
+package com.baeldung.web.upload.client;
+
+import org.springframework.core.io.FileSystemResource;
+import org.springframework.core.io.Resource;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.client.RestTemplate;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+public class MultipartFileUploadClient {
+
+ public static void main(String[] args) throws IOException {
+ uploadSingleFile();
+ uploadMultipleFile();
+ }
+
+ private static void uploadSingleFile() throws IOException {
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.MULTIPART_FORM_DATA);
+
+ MultiValueMap body = new LinkedMultiValueMap<>();
+ body.add("file", getTestFile());
+
+
+ HttpEntity> requestEntity = new HttpEntity<>(body, headers);
+ String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/";
+ RestTemplate restTemplate = new RestTemplate();
+ ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
+ System.out.println("Response code: " + response.getStatusCode());
+ }
+
+ private static void uploadMultipleFile() throws IOException {
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.MULTIPART_FORM_DATA);
+
+ MultiValueMap body = new LinkedMultiValueMap<>();
+ body.add("files", getTestFile());
+ body.add("files", getTestFile());
+ body.add("files", getTestFile());
+
+ HttpEntity> requestEntity = new HttpEntity<>(body, headers);
+ String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/";
+ RestTemplate restTemplate = new RestTemplate();
+ ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
+ System.out.println("Response code: " + response.getStatusCode());
+ }
+
+ public static Resource getTestFile() throws IOException {
+ Path testFile = Files.createTempFile("test-file", ".txt");
+ System.out.println("Creating and Uploading Test File: " + testFile);
+ Files.write(testFile, "Hello World !!, This is a test file.".getBytes());
+ return new FileSystemResource(testFile.toFile());
+ }
+}
diff --git a/spring-rest/src/main/java/com/baeldung/web/upload/controller/FileServerResource.java b/spring-rest/src/main/java/com/baeldung/web/upload/controller/FileServerResource.java
new file mode 100644
index 0000000000..3863a8f20d
--- /dev/null
+++ b/spring-rest/src/main/java/com/baeldung/web/upload/controller/FileServerResource.java
@@ -0,0 +1,43 @@
+package com.baeldung.web.upload.controller;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+import java.util.List;
+
+@RestController
+@RequestMapping("/fileserver")
+public class FileServerResource {
+
+ @RequestMapping(path = "/singlefileupload/", method = RequestMethod.POST)
+ public ResponseEntity processFile(@RequestParam("file") MultipartFile file) throws IOException {
+
+ byte[] bytes = file.getBytes();
+
+ System.out.println("File Name: " + file.getOriginalFilename());
+ System.out.println("File Content Type: " + file.getContentType());
+ System.out.println("File Content:\n" + new String(bytes));
+
+ return (new ResponseEntity<>("Successful", null, HttpStatus.OK));
+ }
+
+ @RequestMapping(path = "/multiplefileupload/", method = RequestMethod.POST)
+ public ResponseEntity processFile(@RequestParam("files") List files) throws IOException {
+
+ for (MultipartFile file : files) {
+ byte[] bytes = file.getBytes();
+
+ System.out.println("File Name: " + file.getOriginalFilename());
+ System.out.println("File Content Type: " + file.getContentType());
+ System.out.println("File Content:\n" + new String(bytes));
+ }
+
+ return (new ResponseEntity<>("Successful", null, HttpStatus.OK));
+ }
+}
\ No newline at end of file
diff --git a/spring-security-anguar/server/src/test/java/com/baeldung/springbootsecurityrest/BasicAuthConfigurationIntegrationTest.java b/spring-security-anguar/server/src/test/java/com/baeldung/springbootsecurityrest/BasicAuthConfigurationIntegrationTest.java
deleted file mode 100644
index 952a0806a1..0000000000
--- a/spring-security-anguar/server/src/test/java/com/baeldung/springbootsecurityrest/BasicAuthConfigurationIntegrationTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-package com.baeldung.springbootsecurityrest;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
-
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.boot.context.embedded.LocalServerPort;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.test.web.client.TestRestTemplate;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.test.context.junit4.SpringRunner;
-
-import com.baeldung.springbootsecurityrest.basicauth.SpringBootSecurityApplication;
-import com.baeldung.springbootsecurityrest.vo.User;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootSecurityApplication.class)
-public class BasicAuthConfigurationIntegrationTest {
-
- TestRestTemplate restTemplate;
- URL base;
-
- @LocalServerPort int port;
-
- @Before
- public void setUp() throws MalformedURLException {
- restTemplate = new TestRestTemplate("user", "password");
- base = new URL("http://localhost:" + port);
- }
-
- @Test
- public void givenCorrectCredentials_whenLogin_ThenSuccess() throws IllegalStateException, IOException {
- restTemplate = new TestRestTemplate();
- User user = new User();
- user.setUserName("user");
- user.setPassword("password");
- ResponseEntity response = restTemplate.postForEntity(base.toString()+"/login",user, String.class);
-
- assertEquals(HttpStatus.OK, response.getStatusCode());
- assertTrue(response
- .getBody()
- .contains("true"));
- }
-
- @Test
- public void givenWrongCredentials_whenLogin_ThenReturnFalse() throws IllegalStateException, IOException {
- restTemplate = new TestRestTemplate();
- User user = new User();
- user.setUserName("user");
- user.setPassword("wrongpassword");
- ResponseEntity response = restTemplate.postForEntity(base.toString()+"/login",user, String.class);
-
- assertEquals(HttpStatus.OK, response.getStatusCode());
- assertTrue(response
- .getBody()
- .contains("false"));
- }
-
- @Test
- public void givenLoggedInUser_whenRequestsHomePage_ThenSuccess() throws IllegalStateException, IOException {
- ResponseEntity response = restTemplate.getForEntity(base.toString()+"/user", String.class);
-
- assertEquals(HttpStatus.OK, response.getStatusCode());
- assertTrue(response
- .getBody()
- .contains("user"));
- }
-
- @Test
- public void givenWrongCredentials_whenRequestsHomePage_ThenUnauthorized() throws IllegalStateException, IOException {
- restTemplate = new TestRestTemplate("user", "wrongpassword");
- ResponseEntity response = restTemplate.getForEntity(base.toString()+"/user", String.class);
-
- assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
- assertTrue(response
- .getBody()
- .contains("Unauthorized"));
- }
-}
diff --git a/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/controller/UserController.java b/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/controller/UserController.java
index 825290ff2d..ab66065b61 100644
--- a/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/controller/UserController.java
+++ b/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/controller/UserController.java
@@ -18,15 +18,12 @@ public class UserController {
@RequestMapping("/login")
public boolean login(@RequestBody User user) {
- if(user.getUserName().equals("user") && user.getPassword().equals("password")) {
- return true;
- }
- return false;
+ return user.getUserName().equals("user") && user.getPassword().equals("password");
}
-
+
@RequestMapping("/user")
public Principal user(HttpServletRequest request) {
String authToken = request.getHeader("Authorization").substring("Basic".length()).trim();
- return () -> new String(Base64.getDecoder().decode(authToken)).split(":")[0];
+ return () -> new String(Base64.getDecoder().decode(authToken)).split(":")[0];
}
}
diff --git a/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java b/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java
index 874856095c..23d13a0ff1 100644
--- a/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java
+++ b/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java
@@ -3,7 +3,6 @@ package org.baeldung.security.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@@ -24,7 +23,7 @@ public class ManualSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
- auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER").and().withUser("admin").password("adminPass").authorities("ROLE_ADMIN");
+ auth.inMemoryAuthentication().withUser("user1").password("{noop}user1Pass").authorities("ROLE_USER").and().withUser("admin").password("adminPass").authorities("ROLE_ADMIN");
}
@Override
@@ -32,7 +31,7 @@ public class ManualSecurityConfig extends WebSecurityConfigurerAdapter {
web.ignoring().antMatchers("/resources/**");
}
- @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
+ @Bean("authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
diff --git a/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java b/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java
index 9600977e37..ca401622c0 100644
--- a/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java
+++ b/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java
@@ -1,6 +1,8 @@
package org.baeldung.security.spring;
+import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@@ -17,7 +19,11 @@ public class SecurityWithCsrfConfig extends WebSecurityConfigurerAdapter {
super();
}
- // java config
+ @Bean("authenticationManager")
+ @Override
+ public AuthenticationManager authenticationManagerBean() throws Exception {
+ return super.authenticationManagerBean();
+ }
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
diff --git a/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java b/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java
index f7dbd5b42c..1067c70fea 100644
--- a/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java
+++ b/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java
@@ -1,6 +1,8 @@
package org.baeldung.security.spring;
+import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@@ -17,7 +19,11 @@ public class SecurityWithoutCsrfConfig extends WebSecurityConfigurerAdapter {
super();
}
- // java config
+ @Bean("authenticationManager")
+ @Override
+ public AuthenticationManager authenticationManagerBean() throws Exception {
+ return super.authenticationManagerBean();
+ }
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java
new file mode 100644
index 0000000000..5eddf3883e
--- /dev/null
+++ b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java
@@ -0,0 +1,22 @@
+package org.baeldung.security;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.authentication.AuthenticationFailureHandler;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Calendar;
+
+public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
+
+ @Override
+ public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
+ httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
+
+ String jsonPayload = "{\"message\" : \"%s\", \"timestamp\" : \"%s\" }";
+ httpServletResponse.getOutputStream().println(String.format(jsonPayload, e.getMessage(), Calendar.getInstance().getTime()));
+ }
+}
diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java
index d9a43d48d0..accc7c9afd 100644
--- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java
+++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java
@@ -1,6 +1,7 @@
package org.baeldung.spring;
import org.baeldung.security.CustomAccessDeniedHandler;
+import org.baeldung.security.CustomAuthenticationFailureHandler;
import org.baeldung.security.CustomLogoutSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -10,6 +11,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.AccessDeniedHandler;
+import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
@Configuration
@@ -26,11 +28,11 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth.inMemoryAuthentication()
- .withUser("user1").password("user1Pass").roles("USER")
- .and()
- .withUser("user2").password("user2Pass").roles("USER")
- .and()
- .withUser("admin").password("adminPass").roles("ADMIN");
+ .withUser("user1").password("user1Pass").roles("USER")
+ .and()
+ .withUser("user2").password("user2Pass").roles("USER")
+ .and()
+ .withUser("admin").password("adminPass").roles("ADMIN");
// @formatter:on
}
@@ -38,23 +40,24 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(final HttpSecurity http) throws Exception {
// @formatter:off
http
- .csrf().disable()
- .authorizeRequests()
- .antMatchers("/admin/**").hasRole("ADMIN")
- .antMatchers("/anonymous*").anonymous()
- .antMatchers("/login*").permitAll()
- .anyRequest().authenticated()
- .and()
- .formLogin()
- .loginPage("/login.html")
- .loginProcessingUrl("/perform_login")
- .defaultSuccessUrl("/homepage.html",true)
- .failureUrl("/login.html?error=true")
- .and()
- .logout()
- .logoutUrl("/perform_logout")
- .deleteCookies("JSESSIONID")
- .logoutSuccessHandler(logoutSuccessHandler());
+ .csrf().disable()
+ .authorizeRequests()
+ .antMatchers("/admin/**").hasRole("ADMIN")
+ .antMatchers("/anonymous*").anonymous()
+ .antMatchers("/login*").permitAll()
+ .anyRequest().authenticated()
+ .and()
+ .formLogin()
+ .loginPage("/login.html")
+ .loginProcessingUrl("/perform_login")
+ .defaultSuccessUrl("/homepage.html", true)
+ //.failureUrl("/login.html?error=true")
+ .failureHandler(authenticationFailureHandler())
+ .and()
+ .logout()
+ .logoutUrl("/perform_logout")
+ .deleteCookies("JSESSIONID")
+ .logoutSuccessHandler(logoutSuccessHandler());
//.and()
//.exceptionHandling().accessDeniedPage("/accessDenied");
//.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
@@ -71,4 +74,8 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
return new CustomAccessDeniedHandler();
}
+ @Bean
+ public AuthenticationFailureHandler authenticationFailureHandler() {
+ return new CustomAuthenticationFailureHandler();
+ }
}
diff --git a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml
index f0fa956934..189522889f 100644
--- a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml
+++ b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml
@@ -15,20 +15,22 @@
-
+
-
+
+
+
diff --git a/spring-security-mvc-login/src/test/java/org/baeldung/security/FormLoginUnitTest.java b/spring-security-mvc-login/src/test/java/org/baeldung/security/FormLoginUnitTest.java
new file mode 100644
index 0000000000..4b3a091e6c
--- /dev/null
+++ b/spring-security-mvc-login/src/test/java/org/baeldung/security/FormLoginUnitTest.java
@@ -0,0 +1,63 @@
+package org.baeldung.security;
+
+import org.baeldung.spring.SecSecurityConfig;
+import org.junit.Before;
+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 org.springframework.test.context.web.WebAppConfiguration;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.MvcResult;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+
+import javax.servlet.Filter;
+
+import static org.junit.Assert.assertTrue;
+import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
+import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = {SecSecurityConfig.class})
+@WebAppConfiguration
+public class FormLoginUnitTest {
+
+ @Autowired
+ private WebApplicationContext context;
+
+ @Autowired
+ private Filter springSecurityFilterChain;
+
+ private MockMvc mvc;
+
+ @Before
+ public void setup() {
+ mvc = MockMvcBuilders
+ .webAppContextSetup(context)
+ .addFilters(springSecurityFilterChain)
+ .build();
+ }
+
+ @Test
+ public void givenValidRequestWithValidCredentials_shouldLoginSuccessfully() throws Exception {
+ mvc
+ .perform(formLogin("/perform_login").user("user1").password("user1Pass"))
+ .andExpect(status().isFound())
+ .andExpect(authenticated().withUsername("user1"));
+ }
+
+ @Test
+ public void givenValidRequestWithInvalidCredentials_shouldFailWith401() throws Exception {
+ MvcResult result = mvc
+ .perform(formLogin("/perform_login").user("random").password("random")).andReturn();
+ /*.andExpect(status().isUnauthorized())
+ .andDo(print())
+ .andExpect(unauthenticated())
+ .andReturn();*/
+
+ assertTrue(result.getResponse().getContentAsString().contains("Bad credentials"));
+ }
+}
diff --git a/spring-security-x509/keystore/Makefile b/spring-security-x509/keystore/Makefile
index 5321be9de3..63498fea76 100644
--- a/spring-security-x509/keystore/Makefile
+++ b/spring-security-x509/keystore/Makefile
@@ -85,4 +85,4 @@ add-client:
clean:
# Remove generated artifacts
- find . ! -name Makefile -type f -exec rm -f {} \;
+ find . \( -name "$(CLIENTNAME)*" -o -name "$(HOSTNAME)*" -o -name "$(KEYSTORE)" -o -name "$(TRUSTSTORE)" -o -name ca.crt \) -type f -exec rm -f {} \;
diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml
index 793e039f62..1afaefd47e 100644
--- a/testing-modules/gatling/pom.xml
+++ b/testing-modules/gatling/pom.xml
@@ -1,119 +1,122 @@
-
- 4.0.0
- org.baeldung
- gatling
- 1.0-SNAPSHOT
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
+
+ 4.0.0
+ org.baeldung
+ gatling
+ 1.0-SNAPSHOT
-
-
- io.gatling.highcharts
- gatling-charts-highcharts
-
-
- io.gatling
- gatling-app
-
-
- io.gatling
- gatling-recorder
-
-
- org.scala-lang
- scala-library
-
-
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+ ../../
+
-
- src/test/scala
-
-
-
- net.alchim31.maven
- scala-maven-plugin
- ${scala-maven-plugin.version}
-
-
-
-
-
- net.alchim31.maven
- scala-maven-plugin
-
-
-
- testCompile
-
-
-
-
- -Ydelambdafy:method
- -target:jvm-1.8
- -deprecation
- -feature
- -unchecked
- -language:implicitConversions
- -language:postfixOps
-
-
-
-
-
-
- io.gatling
- gatling-maven-plugin
- ${gatling-maven-plugin.version}
-
-
- test
-
- execute
-
-
-
-
-
-
+
+
+ io.gatling.highcharts
+ gatling-charts-highcharts
+
+
+ io.gatling
+ gatling-app
+
+
+ io.gatling
+ gatling-recorder
+
+
+ org.scala-lang
+ scala-library
+
+
-
-
-
- io.gatling
- gatling-app
- ${gatling.version}
-
-
- io.gatling
- gatling-recorder
- ${gatling.version}
-
-
- io.gatling.highcharts
- gatling-charts-highcharts
- ${gatling.version}
-
-
- org.scala-lang
- scala-library
- ${scala.version}
-
-
-
+
+ src/test/scala
+
+
+
+ net.alchim31.maven
+ scala-maven-plugin
+ ${scala-maven-plugin.version}
+
+
+
+
+
+ net.alchim31.maven
+ scala-maven-plugin
+
+
+
+ testCompile
+
+
+
+
+ -Ydelambdafy:method
+ -target:jvm-1.8
+ -deprecation
+ -feature
+ -unchecked
+ -language:implicitConversions
+ -language:postfixOps
+
+
+
+
+
+
+ io.gatling
+ gatling-maven-plugin
+ ${gatling-maven-plugin.version}
+
+
+ test
+
+ execute
+
+
+
+
+
+
-
- 1.8
- 1.8
- UTF-8
- 2.11.12
- 2.2.5
- 3.2.2
- 2.2.1
-
+
+
+
+ io.gatling
+ gatling-app
+ ${gatling.version}
+
+
+ io.gatling
+ gatling-recorder
+ ${gatling.version}
+
+
+ io.gatling.highcharts
+ gatling-charts-highcharts
+ ${gatling.version}
+
+
+ org.scala-lang
+ scala-library
+ ${scala.version}
+
+
+
+
+
+ 1.8
+ 1.8
+ UTF-8
+ 2.11.12
+ 2.2.5
+ 3.2.2
+ 2.2.1
+
diff --git a/testing-modules/groovy-spock/pom.xml b/testing-modules/groovy-spock/pom.xml
index f1f0883277..e0da345eb4 100644
--- a/testing-modules/groovy-spock/pom.xml
+++ b/testing-modules/groovy-spock/pom.xml
@@ -6,7 +6,6 @@
groovy-spock
1.0-SNAPSHOT
jar
- Spock Framework - Example Project
com.baeldung
diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md
index 2292c3272a..5a73bca4d6 100644
--- a/testing-modules/junit-5/README.md
+++ b/testing-modules/junit-5/README.md
@@ -13,3 +13,5 @@
- [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall)
- [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration)
- [JUnit5 Programmatic Extension Registration with @RegisterExtension](http://www.baeldung.com/junit-5-registerextension-annotation)
+- [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order)
+
diff --git a/junit5/src/main/java/com/baeldung/junit5/DefaultOrderOfExecutionTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/DefaultOrderOfExecutionUnitTest.java
similarity index 88%
rename from junit5/src/main/java/com/baeldung/junit5/DefaultOrderOfExecutionTest.java
rename to testing-modules/junit-5/src/test/java/com/baeldung/methodorders/DefaultOrderOfExecutionUnitTest.java
index 15b07ee03a..c269a0e9b6 100644
--- a/junit5/src/main/java/com/baeldung/junit5/DefaultOrderOfExecutionTest.java
+++ b/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/DefaultOrderOfExecutionUnitTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.junit5;
+package com.baeldung.methodorders;
import static org.junit.Assert.assertEquals;
@@ -8,7 +8,7 @@ import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.DEFAULT)
-public class DefaultOrderOfExecutionTest {
+public class DefaultOrderOfExecutionUnitTest {
private static StringBuilder output = new StringBuilder("");
@Test
diff --git a/junit5/src/main/java/com/baeldung/junit5/JVMOrderOfExecutionTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/JVMOrderOfExecutionUnitTest.java
similarity index 84%
rename from junit5/src/main/java/com/baeldung/junit5/JVMOrderOfExecutionTest.java
rename to testing-modules/junit-5/src/test/java/com/baeldung/methodorders/JVMOrderOfExecutionUnitTest.java
index 189efc8945..c4996dacf3 100644
--- a/junit5/src/main/java/com/baeldung/junit5/JVMOrderOfExecutionTest.java
+++ b/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/JVMOrderOfExecutionUnitTest.java
@@ -1,11 +1,11 @@
-package com.baeldung.junit5;
+package com.baeldung.methodorders;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.JVM)
-public class JVMOrderOfExecutionTest {
+public class JVMOrderOfExecutionUnitTest {
private static StringBuilder output = new StringBuilder("");
diff --git a/junit5/src/main/java/com/baeldung/junit5/NameAscendingOrderOfExecutionTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/NameAscendingOrderOfExecutionUnitTest.java
similarity index 87%
rename from junit5/src/main/java/com/baeldung/junit5/NameAscendingOrderOfExecutionTest.java
rename to testing-modules/junit-5/src/test/java/com/baeldung/methodorders/NameAscendingOrderOfExecutionUnitTest.java
index 88de057fc8..032bc81779 100644
--- a/junit5/src/main/java/com/baeldung/junit5/NameAscendingOrderOfExecutionTest.java
+++ b/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/NameAscendingOrderOfExecutionUnitTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.junit5;
+package com.baeldung.methodorders;
import static org.junit.Assert.assertEquals;
@@ -8,7 +8,7 @@ import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class NameAscendingOrderOfExecutionTest {
+public class NameAscendingOrderOfExecutionUnitTest {
private static StringBuilder output = new StringBuilder("");
@Test
diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockAnnotationUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockAnnotationUnitTest.java
index 5d565fea88..fcc646e8ea 100644
--- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockAnnotationUnitTest.java
+++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockAnnotationUnitTest.java
@@ -15,18 +15,22 @@ public class MockAnnotationUnitTest {
UserRepository mockRepository;
@Test
- public void testMockAnnotation() {
+ public void givenCountMethodMocked_WhenCountInvoked_ThenMockValueReturned() {
Mockito.when(mockRepository.count()).thenReturn(123L);
+
long userCount = mockRepository.count();
+
Assert.assertEquals(123L, userCount);
Mockito.verify(mockRepository).count();
}
@Test
- public void testMockitoMockMethod() {
+ public void givenCountMethodOfLocalMockVariableMocked_WhenCountInvoked_ThenMockedValueReturned() {
UserRepository localMockRepository = Mockito.mock(UserRepository.class);
Mockito.when(localMockRepository.count()).thenReturn(111L);
+
long userCount = localMockRepository.count();
+
Assert.assertEquals(111L, userCount);
Mockito.verify(localMockRepository).count();
}
diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockBeanAnnotationIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockBeanAnnotationIntegrationTest.java
index 008e674696..fd9236fe13 100644
--- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockBeanAnnotationIntegrationTest.java
+++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockBeanAnnotationIntegrationTest.java
@@ -20,10 +20,12 @@ public class MockBeanAnnotationIntegrationTest {
ApplicationContext context;
@Test
- public void testMockBean() {
+ public void givenCountMethodMocked_WhenCountInvokedOnBeanFromContext_ThenMockValueReturned() {
Mockito.when(mockRepository.count()).thenReturn(123L);
+
UserRepository userRepoFromContext = context.getBean(UserRepository.class);
long userCount = userRepoFromContext.count();
+
Assert.assertEquals(123L, userCount);
Mockito.verify(mockRepository).count();
}
diff --git a/undertow/pom.xml b/undertow/pom.xml
index 15388e278c..d000956aee 100644
--- a/undertow/pom.xml
+++ b/undertow/pom.xml
@@ -1,7 +1,7 @@
4.0.0
-
+
com.baeldung.undertow
undertow
jar
@@ -29,6 +29,7 @@
org.apache.maven.plugins
maven-shade-plugin
+ ${maven-shade-plugin.version}
package
@@ -41,6 +42,7 @@
org.apache.maven.plugins
maven-jar-plugin
+ ${maven-jar-plugin.version}
@@ -54,6 +56,8 @@
1.4.18.Final
+ 2.4.3
+ 3.0.2
\ No newline at end of file