Merge branch 'master' into SpringReactiveKotlin
This commit is contained in:
commit
8d15be58c0
@ -19,7 +19,7 @@ In additional to Spring, the following technologies are in focus: `core Java`, `
|
|||||||
|
|
||||||
Building the project
|
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
|
Working with the code in Eclipse
|
||||||
|
88
apache-avro/pom.xml
Normal file
88
apache-avro/pom.xml
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>apache-avro-tutorial</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<compiler-plugin.version>3.5</compiler-plugin.version>
|
||||||
|
<avro.version>1.8.2</avro.version>
|
||||||
|
<java.version>1.8</java.version>
|
||||||
|
<slf4j.version>1.7.25</slf4j.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.10</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-simple</artifactId>
|
||||||
|
<version>${slf4j.version}</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.avro</groupId>
|
||||||
|
<artifactId>avro</artifactId>
|
||||||
|
<version>${avro.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.avro</groupId>
|
||||||
|
<artifactId>avro-compiler</artifactId>
|
||||||
|
<version>${avro.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.avro</groupId>
|
||||||
|
<artifactId>avro-maven-plugin</artifactId>
|
||||||
|
<version>${avro.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>${java.version}</source>
|
||||||
|
<target>${java.version}</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.avro</groupId>
|
||||||
|
<artifactId>avro-maven-plugin</artifactId>
|
||||||
|
<version>${avro.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>schemas</id>
|
||||||
|
<phase>generate-sources</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>schema</goal>
|
||||||
|
<goal>protocol</goal>
|
||||||
|
<goal>idl-protocol</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<sourceDirectory>${project.basedir}/src/main/resources/</sourceDirectory>
|
||||||
|
<outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
@ -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"));
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -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$; }
|
||||||
|
}
|
@ -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<AvroHttpRequest> ENCODER =
|
||||||
|
new BinaryMessageEncoder<AvroHttpRequest>(MODEL$, SCHEMA$);
|
||||||
|
|
||||||
|
private static final BinaryMessageDecoder<AvroHttpRequest> DECODER =
|
||||||
|
new BinaryMessageDecoder<AvroHttpRequest>(MODEL$, SCHEMA$);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the BinaryMessageDecoder instance used by this class.
|
||||||
|
*/
|
||||||
|
public static BinaryMessageDecoder<AvroHttpRequest> 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<AvroHttpRequest> createDecoder(SchemaStore resolver) {
|
||||||
|
return new BinaryMessageDecoder<AvroHttpRequest>(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<java.lang.CharSequence> 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 <code>newBuilder()</code>.
|
||||||
|
*/
|
||||||
|
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<java.lang.CharSequence> 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<java.lang.CharSequence>)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<java.lang.CharSequence> getEmployeeNames() {
|
||||||
|
return employeeNames;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the value of the 'employeeNames' field.
|
||||||
|
* @param value the value to set.
|
||||||
|
*/
|
||||||
|
public void setEmployeeNames(java.util.List<java.lang.CharSequence> 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<AvroHttpRequest>
|
||||||
|
implements org.apache.avro.data.RecordBuilder<AvroHttpRequest> {
|
||||||
|
|
||||||
|
private long requestTime;
|
||||||
|
private ClientIdentifier clientIdentifier;
|
||||||
|
private ClientIdentifier.Builder clientIdentifierBuilder;
|
||||||
|
private java.util.List<java.lang.CharSequence> 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<java.lang.CharSequence> 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<java.lang.CharSequence> 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<java.lang.CharSequence>) 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<AvroHttpRequest>
|
||||||
|
WRITER$ = (org.apache.avro.io.DatumWriter<AvroHttpRequest>)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<AvroHttpRequest>
|
||||||
|
READER$ = (org.apache.avro.io.DatumReader<AvroHttpRequest>)MODEL$.createDatumReader(SCHEMA$);
|
||||||
|
|
||||||
|
@Override public void readExternal(java.io.ObjectInput in)
|
||||||
|
throws java.io.IOException {
|
||||||
|
READER$.read(this, SpecificData.getDecoder(in));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<ClientIdentifier> ENCODER =
|
||||||
|
new BinaryMessageEncoder<ClientIdentifier>(MODEL$, SCHEMA$);
|
||||||
|
|
||||||
|
private static final BinaryMessageDecoder<ClientIdentifier> DECODER =
|
||||||
|
new BinaryMessageDecoder<ClientIdentifier>(MODEL$, SCHEMA$);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the BinaryMessageDecoder instance used by this class.
|
||||||
|
*/
|
||||||
|
public static BinaryMessageDecoder<ClientIdentifier> 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<ClientIdentifier> createDecoder(SchemaStore resolver) {
|
||||||
|
return new BinaryMessageDecoder<ClientIdentifier>(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 <code>newBuilder()</code>.
|
||||||
|
*/
|
||||||
|
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<ClientIdentifier>
|
||||||
|
implements org.apache.avro.data.RecordBuilder<ClientIdentifier> {
|
||||||
|
|
||||||
|
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<ClientIdentifier>
|
||||||
|
WRITER$ = (org.apache.avro.io.DatumWriter<ClientIdentifier>)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<ClientIdentifier>
|
||||||
|
READER$ = (org.apache.avro.io.DatumReader<ClientIdentifier>)MODEL$.createDatumReader(SCHEMA$);
|
||||||
|
|
||||||
|
@Override public void readExternal(java.io.ObjectInput in)
|
||||||
|
throws java.io.IOException {
|
||||||
|
READER$.read(this, SpecificData.getDecoder(in));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<AvroHttpRequest> 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<AvroHttpRequest> employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
|
||||||
|
Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);
|
||||||
|
try {
|
||||||
|
return employeeReader.read(null, decoder);
|
||||||
|
} catch (IOException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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<AvroHttpRequest> 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<AvroHttpRequest> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
47
apache-avro/src/main/resources/avroHttpRequest-schema.avsc
Normal file
47
apache-avro/src/main/resources/avroHttpRequest-schema.avsc
Normal file
@ -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"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
@ -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<CharSequence> 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()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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<Integer, Animal> convertListBeforeJava8(List<Animal> list) {
|
||||||
|
Map<Integer, Animal> map = new HashMap<Integer, Animal>();
|
||||||
|
for (Animal animal : list) {
|
||||||
|
map.put(animal.getId(), animal);
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<Integer, Animal> convertListAfterJava8(List<Animal> list) {
|
||||||
|
Map<Integer, Animal> map = list.stream().collect(Collectors.toMap(Animal::getId, animal -> animal));
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<Integer, Animal> convertListWithGuava(List<Animal> list) {
|
||||||
|
|
||||||
|
Map<Integer, Animal> map = Maps.uniqueIndex(list, Animal::getId);
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<Integer, Animal> convertListWithApacheCommons1(List<Animal> list) {
|
||||||
|
|
||||||
|
Map<Integer, Animal> map = new HashMap<Integer, Animal>();
|
||||||
|
|
||||||
|
IterableUtils.forEach(list, animal -> {
|
||||||
|
map.put(animal.getId(), animal);
|
||||||
|
});
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<Integer, Animal> convertListWithApacheCommons2(List<Animal> list) {
|
||||||
|
|
||||||
|
Map<Integer, Animal> map = new HashMap<Integer, Animal>();
|
||||||
|
|
||||||
|
MapUtils.populateMap(map, list, Animal::getId);
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
}
|
@ -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<Animal> 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<Integer, Animal> map = convertListService.convertListBeforeJava8(list);
|
||||||
|
|
||||||
|
assertThat(map.values(), containsInAnyOrder(list.toArray()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenConvertAfterJava8_thenReturnMapWithTheSameElements() {
|
||||||
|
|
||||||
|
Map<Integer, Animal> map = convertListService.convertListAfterJava8(list);
|
||||||
|
|
||||||
|
assertThat(map.values(), containsInAnyOrder(list.toArray()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenConvertWithGuava_thenReturnMapWithTheSameElements() {
|
||||||
|
|
||||||
|
Map<Integer, Animal> map = convertListService.convertListWithGuava(list);
|
||||||
|
|
||||||
|
assertThat(map.values(), containsInAnyOrder(list.toArray()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenConvertWithApacheCommons1_thenReturnMapWithTheSameElements() {
|
||||||
|
|
||||||
|
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons1(list);
|
||||||
|
|
||||||
|
assertThat(map.values(), containsInAnyOrder(list.toArray()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenConvertWithApacheCommons2_thenReturnMapWithTheSameElements() {
|
||||||
|
|
||||||
|
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons2(list);
|
||||||
|
|
||||||
|
assertThat(map.values(), containsInAnyOrder(list.toArray()));
|
||||||
|
}
|
||||||
|
}
|
@ -50,22 +50,9 @@ public class HashSetInitalizingUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingJava8_usingCollectOnStream_thenCorrectSize() {
|
public void whenUsingJava8_usingCollectOnStream_thenCorrectSize() {
|
||||||
Set<String> set = Stream.of("a", "b", "c").collect(Collectors.toSet());
|
Set<String> set = Stream.of("a", "b", "c").collect(Collectors.toCollection(HashSet::new));
|
||||||
assertEquals(3, set.size());
|
assertEquals(3, set.size());
|
||||||
}
|
}
|
||||||
@Test
|
|
||||||
public void whenUsingJava8_fromStringArray_thenCorrectSize() {
|
|
||||||
String[] stringArray = {"a","b","c"};
|
|
||||||
Set<String> set = Arrays.stream(stringArray).collect(Collectors.toCollection(HashSet::new));
|
|
||||||
assertEquals(3, set.size());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Requires Java9 - uncomment if you are using Java 9 or higher
|
|
||||||
/*@Test
|
|
||||||
public void whenUsingJava9_usingCollectOnStream_thenCorrectSize() {
|
|
||||||
Set set = Set.of("a", "b", "c");
|
|
||||||
assertEquals(3, set.size());
|
|
||||||
}*/
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingGoogleGuava_createMutableSet_thenCorrectSize() {
|
public void whenUsingGoogleGuava_createMutableSet_thenCorrectSize() {
|
||||||
@ -78,4 +65,6 @@ public class HashSetInitalizingUnitTest {
|
|||||||
Set<String> set = ImmutableSet.of("a", "b", "c");
|
Set<String> set = ImmutableSet.of("a", "b", "c");
|
||||||
assertEquals(3, set.size());
|
assertEquals(3, set.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -60,7 +60,6 @@
|
|||||||
<groupId>org.jetbrains.kotlin</groupId>
|
<groupId>org.jetbrains.kotlin</groupId>
|
||||||
<artifactId>kotlin-reflect</artifactId>
|
<artifactId>kotlin-reflect</artifactId>
|
||||||
<version>${kotlin-reflect.version}</version>
|
<version>${kotlin-reflect.version}</version>
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jetbrains.kotlinx</groupId>
|
<groupId>org.jetbrains.kotlinx</groupId>
|
||||||
@ -224,10 +223,11 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<kotlin-maven-plugin.version>1.2.41</kotlin-maven-plugin.version>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<kotlin-test-junit.version>1.2.41</kotlin-test-junit.version>
|
<kotlin-maven-plugin.version>1.2.51</kotlin-maven-plugin.version>
|
||||||
<kotlin-stdlib.version>1.2.41</kotlin-stdlib.version>
|
<kotlin-test-junit.version>1.2.51</kotlin-test-junit.version>
|
||||||
<kotlin-reflect.version>1.2.41</kotlin-reflect.version>
|
<kotlin-stdlib.version>1.2.51</kotlin-stdlib.version>
|
||||||
|
<kotlin-reflect.version>1.2.51</kotlin-reflect.version>
|
||||||
<kotlinx.version>0.22.5</kotlinx.version>
|
<kotlinx.version>0.22.5</kotlinx.version>
|
||||||
<ktor.io.version>0.9.2</ktor.io.version>
|
<ktor.io.version>0.9.2</ktor.io.version>
|
||||||
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
||||||
|
@ -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 : Any> T.logger(): Logger = getLogger(getClassForLogging(javaClass))
|
||||||
|
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
LoggerAsExtensionOnAny().log("test")
|
||||||
|
ExtensionSubclass().log("sub")
|
||||||
|
"foo".logger().info("foo")
|
||||||
|
1.logger().info("uh-oh!")
|
||||||
|
SomeOtherClass().logger()
|
||||||
|
}
|
||||||
|
|
||||||
|
class SomeOtherClass {
|
||||||
|
fun logger(): String {
|
||||||
|
return "foo"
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.kotlin.logging
|
||||||
|
|
||||||
|
import org.slf4j.Logger
|
||||||
|
import org.slf4j.LoggerFactory
|
||||||
|
|
||||||
|
interface Logging
|
||||||
|
|
||||||
|
inline fun <reified T : Logging> 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<String>) {
|
||||||
|
LoggerAsExtensionOnMarkerInterface().log("test")
|
||||||
|
MarkerExtensionSubclass().log("sub")
|
||||||
|
"foo".logger().info("foo")
|
||||||
|
}
|
@ -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<String>) {
|
||||||
|
LoggerAsProperty().log("test")
|
||||||
|
PropertySubclass().log("sub")
|
||||||
|
}
|
@ -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<Logger> =
|
||||||
|
lazy { getLogger(getClassForLogging(forClass)) }
|
||||||
|
|
||||||
|
fun <T : Any> T.lazyLogger(): Lazy<Logger> = lazyLogger(javaClass)
|
||||||
|
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
LoggerAsPropertyDelegate().log("test")
|
||||||
|
DelegateSubclass().log("sub")
|
||||||
|
}
|
||||||
|
|
||||||
|
class LoggerDelegate<in R : Any> : ReadOnlyProperty<R, Logger> {
|
||||||
|
override fun getValue(thisRef: R, property: KProperty<*>) =
|
||||||
|
getLogger(getClassForLogging(thisRef.javaClass))
|
||||||
|
}
|
@ -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<String>) {
|
||||||
|
LoggerInCompanionObject().log("test")
|
||||||
|
LoggerInCompanionObject.Inner().log("test")
|
||||||
|
CompanionSubclass().log("sub")
|
||||||
|
}
|
@ -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 <T : Any> getClassForLogging(javaClass: Class<T>): Class<*> {
|
||||||
|
return javaClass.enclosingClass?.takeIf {
|
||||||
|
it.kotlin.companionObject?.java == javaClass
|
||||||
|
} ?: javaClass
|
||||||
|
}
|
@ -1,7 +1,7 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>geotools</artifactId>
|
<artifactId>geotools</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
@ -58,4 +58,5 @@
|
|||||||
<geotools-swing.version>15.2</geotools-swing.version>
|
<geotools-swing.version>15.2</geotools-swing.version>
|
||||||
<geotools-shapefile.version>15.2</geotools-shapefile.version>
|
<geotools-shapefile.version>15.2</geotools-shapefile.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -5,8 +5,6 @@
|
|||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>hibernate5</artifactId>
|
<artifactId>hibernate5</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<name>hibernate5</name>
|
|
||||||
<url>http://maven.apache.org</url>
|
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
@ -59,9 +57,6 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<!-- Maven plugins -->
|
|
||||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
|
||||||
<hibernate.version>5.3.2.Final</hibernate.version>
|
<hibernate.version>5.3.2.Final</hibernate.version>
|
||||||
<mysql.version>6.0.6</mysql.version>
|
<mysql.version>6.0.6</mysql.version>
|
||||||
<mariaDB4j.version>2.2.3</mariaDB4j.version>
|
<mariaDB4j.version>2.2.3</mariaDB4j.version>
|
||||||
|
13
hibernate5/src/main/resources/logback.xml
Normal file
13
hibernate5/src/main/resources/logback.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern> %date [%thread] %-5level %logger{36} - %message%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -3,28 +3,9 @@
|
|||||||
<configuration scan="true">
|
<configuration scan="true">
|
||||||
<include resource="org/springframework/boot/logging/logback/base.xml"/>
|
<include resource="org/springframework/boot/logging/logback/base.xml"/>
|
||||||
|
|
||||||
<!-- The FILE and ASYNC appenders are here as examples for a production configuration -->
|
<logger name="com.baeldung" level="INFO"/>
|
||||||
<!--
|
|
||||||
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
|
||||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
|
||||||
<fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
|
|
||||||
<maxHistory>90</maxHistory>
|
|
||||||
</rollingPolicy>
|
|
||||||
<encoder>
|
|
||||||
<charset>utf-8</charset>
|
|
||||||
<Pattern>%d %-5level [%thread] %logger{0}: %msg%n</Pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
|
<logger name="io.github.jhipster" level="INFO"/>
|
||||||
<queueSize>512</queueSize>
|
|
||||||
<appender-ref ref="FILE"/>
|
|
||||||
</appender>
|
|
||||||
-->
|
|
||||||
|
|
||||||
<logger name="com.baeldung" level="#logback.loglevel#"/>
|
|
||||||
|
|
||||||
<logger name="io.github.jhipster" level="DEBUG"/>
|
|
||||||
|
|
||||||
<logger name="javax.activation" level="WARN"/>
|
<logger name="javax.activation" level="WARN"/>
|
||||||
<logger name="javax.mail" level="WARN"/>
|
<logger name="javax.mail" level="WARN"/>
|
||||||
|
88
jnosql/jnosql-artemis/pom.xml
Normal file
88
jnosql/jnosql-artemis/pom.xml
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.jnosql</groupId>
|
||||||
|
<artifactId>jnosql</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>jnosql-artemis</artifactId>
|
||||||
|
<packaging>war</packaging>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
|
||||||
|
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>${artifactId}</finalName>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>net.wasdev.wlp.maven.plugins</groupId>
|
||||||
|
<artifactId>liberty-maven-plugin</artifactId>
|
||||||
|
<version>${liberty-maven-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<assemblyArtifact>
|
||||||
|
<groupId>io.openliberty</groupId>
|
||||||
|
<artifactId>openliberty-webProfile8</artifactId>
|
||||||
|
<version>RELEASE</version>
|
||||||
|
<type>zip</type>
|
||||||
|
</assemblyArtifact>
|
||||||
|
<installAppPackages>project</installAppPackages>
|
||||||
|
<looseApplication>true</looseApplication>
|
||||||
|
<configFile>src/main/liberty/config/server.xml</configFile>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>install-server</id>
|
||||||
|
<phase>prepare-package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>install-server</goal>
|
||||||
|
<goal>create-server</goal>
|
||||||
|
<goal>install-feature</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>install-apps</id>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>install-apps</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax</groupId>
|
||||||
|
<artifactId>javaee-web-api</artifactId>
|
||||||
|
<version>8.0</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.artemis</groupId>
|
||||||
|
<artifactId>artemis-configuration</artifactId>
|
||||||
|
<version>${jnosql.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.artemis</groupId>
|
||||||
|
<artifactId>artemis-document</artifactId>
|
||||||
|
<version>${jnosql.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>mongodb-driver</artifactId>
|
||||||
|
<version>${jnosql.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
@ -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 {
|
||||||
|
}
|
@ -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 !");
|
||||||
|
}
|
||||||
|
}
|
@ -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<MongoDBDocumentCollectionManager> managerFactory;
|
||||||
|
|
||||||
|
@Produces
|
||||||
|
public DocumentCollectionManager getEntityManager() {
|
||||||
|
return managerFactory.get(DATABASE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void close(@Disposes DocumentCollectionManager entityManager) {
|
||||||
|
entityManager.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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> todo = repository.findById(id);
|
||||||
|
return todo.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Todo> getAll() {
|
||||||
|
return repository.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void delete(String id) {
|
||||||
|
repository.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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> todo = documentTemplate.find(Todo.class, id);
|
||||||
|
return todo.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Todo> getAll() {
|
||||||
|
DocumentQuery query = select().from("Todo").build();
|
||||||
|
return documentTemplate.select(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void delete(String id) {
|
||||||
|
documentTemplate.delete(Todo.class, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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<Todo> getAll();
|
||||||
|
|
||||||
|
void delete(String id);
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.jnosql.artemis;
|
||||||
|
|
||||||
|
import org.jnosql.artemis.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface TodoRepository extends Repository<Todo, String> {
|
||||||
|
List<Todo> findByName(String name);
|
||||||
|
List<Todo> findAll();
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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 {
|
||||||
|
}
|
@ -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 {
|
||||||
|
}
|
6
jnosql/jnosql-artemis/src/main/liberty/config/server.xml
Normal file
6
jnosql/jnosql-artemis/src/main/liberty/config/server.xml
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
<server description="OpenLiberty Server">
|
||||||
|
<featureManager>
|
||||||
|
<feature>webProfile-8.0</feature>
|
||||||
|
</featureManager>
|
||||||
|
<httpEndpoint httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint" host="*"/>
|
||||||
|
</server>
|
@ -0,0 +1,6 @@
|
|||||||
|
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||||
|
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||||
|
bean-discovery-mode="all">
|
||||||
|
</beans>
|
@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
10
jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json
Normal file
10
jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json
Normal file
@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
93
jnosql/jnosql-diana/pom.xml
Normal file
93
jnosql/jnosql-diana/pom.xml
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.jnosql</groupId>
|
||||||
|
<artifactId>jnosql</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>jnosql-diana</artifactId>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
|
<version>1.6.0</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>document</id>
|
||||||
|
<goals>
|
||||||
|
<goal>java</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<mainClass>com.baeldung.jnosql.diana.document.DocumentApp</mainClass>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>column</id>
|
||||||
|
<goals>
|
||||||
|
<goal>java</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<mainClass>com.baeldung.jnosql.diana.column.ColumnFamilyApp</mainClass>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>key</id>
|
||||||
|
<goals>
|
||||||
|
<goal>java</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<mainClass>com.baeldung.jnosql.diana.key.KeyValueApp</mainClass>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<!--NoSQL Document oriented-->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>diana-document</artifactId>
|
||||||
|
<version>0.0.5</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>mongodb-driver</artifactId>
|
||||||
|
<version>0.0.5</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!--NoSQL Column oriented-->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>diana-column</artifactId>
|
||||||
|
<version>0.0.5</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>cassandra-driver</artifactId>
|
||||||
|
<version>0.0.5</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!--NoSQL Key Value oriented-->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>diana-key-value</artifactId>
|
||||||
|
<version>0.0.5</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>hazelcast-driver</artifactId>
|
||||||
|
<version>0.0.5</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<String, Object> 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<DocumentEntity> 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<DocumentEntity> documentEntityList = manager.select(select().from(DOCUMENT_COLLECTION).build());
|
||||||
|
System.out.println(documentEntityList);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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 +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
}
|
@ -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<Value> optionalValue = manager.get("12345");
|
||||||
|
Value value = optionalValue.get();
|
||||||
|
Book savedBook = value.get(Book.class);
|
||||||
|
System.out.println(savedBook);
|
||||||
|
}
|
||||||
|
Hazelcast.shutdownAll();
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
@ -0,0 +1 @@
|
|||||||
|
hazelcast-instanceName=hazelcast
|
@ -0,0 +1,2 @@
|
|||||||
|
#Define Host and Port
|
||||||
|
mongodb-server-host-1=localhost:27017
|
23
jnosql/pom.xml
Normal file
23
jnosql/pom.xml
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<groupId>com.baeldung.jnosql</groupId>
|
||||||
|
<artifactId>jnosql</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
|
<jnosql.version>0.0.5</jnosql.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<modules>
|
||||||
|
<module>jnosql-diana</module>
|
||||||
|
<module>jnosql-artemis</module>
|
||||||
|
</modules>
|
||||||
|
|
||||||
|
</project>
|
@ -1,2 +0,0 @@
|
|||||||
## Relevant articles:
|
|
||||||
- [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order)
|
|
@ -772,6 +772,12 @@
|
|||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.googlecode.jmapper-framework</groupId>
|
||||||
|
<artifactId>jmapper-core</artifactId>
|
||||||
|
<version>${jmapper.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<repositories>
|
<repositories>
|
||||||
@ -1015,6 +1021,7 @@
|
|||||||
<jersey.version>1.19.4</jersey.version>
|
<jersey.version>1.19.4</jersey.version>
|
||||||
<javalin.version>1.6.0</javalin.version>
|
<javalin.version>1.6.0</javalin.version>
|
||||||
<fugue.version>4.5.1</fugue.version>
|
<fugue.version>4.5.1</fugue.version>
|
||||||
|
<jmapper.version>1.6.0.1</jmapper.version>
|
||||||
<maven-bundle-plugin.version>3.3.0</maven-bundle-plugin.version>
|
<maven-bundle-plugin.version>3.3.0</maven-bundle-plugin.version>
|
||||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
56
libraries/src/main/java/com/baeldung/jmapper/User.java
Normal file
56
libraries/src/main/java/com/baeldung/jmapper/User.java
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
package com.baeldung.jmapper;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
|
||||||
|
public class User {
|
||||||
|
|
||||||
|
private long id;
|
||||||
|
private String email;
|
||||||
|
private LocalDate birthDate;
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
|
||||||
|
public User() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public User(long id, String email, LocalDate birthDate) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.email = email;
|
||||||
|
this.birthDate = birthDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDate getBirthDate() {
|
||||||
|
return birthDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBirthDate(LocalDate birthDate) {
|
||||||
|
this.birthDate = birthDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "User [id=" + id + ", email=" + email + ", birthDate=" + birthDate + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
69
libraries/src/main/java/com/baeldung/jmapper/UserDto.java
Normal file
69
libraries/src/main/java/com/baeldung/jmapper/UserDto.java
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
package com.baeldung.jmapper;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.Period;
|
||||||
|
|
||||||
|
import com.googlecode.jmapper.annotations.JMap;
|
||||||
|
import com.googlecode.jmapper.annotations.JMapConversion;
|
||||||
|
|
||||||
|
public class UserDto {
|
||||||
|
|
||||||
|
@JMap
|
||||||
|
private long id;
|
||||||
|
|
||||||
|
@JMap("email")
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@JMap("birthDate")
|
||||||
|
private int age;
|
||||||
|
|
||||||
|
@JMapConversion(from={"birthDate"}, to={"age"})
|
||||||
|
public int conversion(LocalDate birthDate){
|
||||||
|
return Period.between(birthDate, LocalDate.now()).getYears();
|
||||||
|
}
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
|
||||||
|
public UserDto() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserDto(long id, String username, int age) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.username = username;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUsername() {
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUsername(String username) {
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAge(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "UserDto [id=" + id + ", username=" + username + ", age=" + age + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
47
libraries/src/main/java/com/baeldung/jmapper/UserDto1.java
Normal file
47
libraries/src/main/java/com/baeldung/jmapper/UserDto1.java
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.jmapper;
|
||||||
|
|
||||||
|
import com.googlecode.jmapper.annotations.JGlobalMap;
|
||||||
|
|
||||||
|
@JGlobalMap
|
||||||
|
public class UserDto1 {
|
||||||
|
|
||||||
|
private long id;
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
|
||||||
|
public UserDto1() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserDto1(long id, String email) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "UserDto [id=" + id + ", email=" + email + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,49 @@
|
|||||||
|
package com.baeldung.jmapper.relational;
|
||||||
|
|
||||||
|
import com.googlecode.jmapper.annotations.JMap;
|
||||||
|
|
||||||
|
|
||||||
|
public class User {
|
||||||
|
|
||||||
|
@JMap(classes = {UserDto1.class, UserDto2.class})
|
||||||
|
private long id;
|
||||||
|
|
||||||
|
@JMap(attributes = {"username", "email"}, classes = {UserDto1.class, UserDto2.class})
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
|
||||||
|
public User() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public User(long id, String email) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "User [id=" + id + ", email=" + email + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.jmapper.relational;
|
||||||
|
|
||||||
|
|
||||||
|
public class UserDto1 {
|
||||||
|
|
||||||
|
private long id;
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
|
||||||
|
public UserDto1() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserDto1(long id, String username) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUsername() {
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUsername(String username) {
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "UserDto [id=" + id + ", username=" + username + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.jmapper.relational;
|
||||||
|
|
||||||
|
|
||||||
|
public class UserDto2 {
|
||||||
|
|
||||||
|
private long id;
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
|
||||||
|
public UserDto2() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserDto2(long id, String email) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "UserDto2 [id=" + id + ", email=" + email + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
10
libraries/src/main/resources/user_jmapper.xml
Normal file
10
libraries/src/main/resources/user_jmapper.xml
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
<jmapper>
|
||||||
|
<class name="com.baeldung.jmapper.UserDto">
|
||||||
|
<attribute name="id">
|
||||||
|
<value name="id"/>
|
||||||
|
</attribute>
|
||||||
|
<attribute name="username">
|
||||||
|
<value name="email"/>
|
||||||
|
</attribute>
|
||||||
|
</class>
|
||||||
|
</jmapper>
|
5
libraries/src/main/resources/user_jmapper1.xml
Normal file
5
libraries/src/main/resources/user_jmapper1.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<jmapper>
|
||||||
|
<class name="com.baeldung.jmapper.UserDto1">
|
||||||
|
<global/>
|
||||||
|
</class>
|
||||||
|
</jmapper>
|
21
libraries/src/main/resources/user_jmapper2.xml
Normal file
21
libraries/src/main/resources/user_jmapper2.xml
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
<jmapper>
|
||||||
|
<class name="com.baeldung.jmapper.relational.User">
|
||||||
|
<attribute name="id">
|
||||||
|
<value name="id"/>
|
||||||
|
<classes>
|
||||||
|
<class name="com.baeldung.jmapper.relational.UserDto1"/>
|
||||||
|
<class name="com.baeldung.jmapper.relational.UserDto2"/>
|
||||||
|
</classes>
|
||||||
|
</attribute>
|
||||||
|
<attribute name="email">
|
||||||
|
<attributes>
|
||||||
|
<attribute name="username"/>
|
||||||
|
<attribute name="email"/>
|
||||||
|
</attributes>
|
||||||
|
<classes>
|
||||||
|
<class name="com.baeldung.jmapper.relational.UserDto1"/>
|
||||||
|
<class name="com.baeldung.jmapper.relational.UserDto2"/>
|
||||||
|
</classes>
|
||||||
|
</attribute>
|
||||||
|
</class>
|
||||||
|
</jmapper>
|
@ -31,7 +31,7 @@ import org.springframework.web.client.RestTemplate;
|
|||||||
import io.specto.hoverfly.junit.core.SimulationSource;
|
import io.specto.hoverfly.junit.core.SimulationSource;
|
||||||
import io.specto.hoverfly.junit.rule.HoverflyRule;
|
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'}")))
|
private static final SimulationSource source = dsl(service("http://www.baeldung.com").get("/api/courses/1").willReturn(success().body(jsonWithSingleQuotes("{'id':'1','name':'HCI'}")))
|
||||||
|
|
@ -5,7 +5,7 @@ import org.junit.Test;
|
|||||||
|
|
||||||
import static org.assertj.core.api.Java6Assertions.assertThat;
|
import static org.assertj.core.api.Java6Assertions.assertThat;
|
||||||
|
|
||||||
public class HelloWorldServiceIntegrationTest extends AbstractIntegrationTest {
|
public class HelloWorldServiceTemporaryLiveTest extends AbstractIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGetIsCalledTwoTimes_thenTheSecondShouldHitTheCache() {
|
public void whenGetIsCalledTwoTimes_thenTheSecondShouldHitTheCache() {
|
@ -0,0 +1,114 @@
|
|||||||
|
package com.baeldung.jmapper;
|
||||||
|
|
||||||
|
import static com.googlecode.jmapper.api.JMapperAPI.attribute;
|
||||||
|
import static com.googlecode.jmapper.api.JMapperAPI.global;
|
||||||
|
import static com.googlecode.jmapper.api.JMapperAPI.mappedClass;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.googlecode.jmapper.JMapper;
|
||||||
|
import com.googlecode.jmapper.api.JMapperAPI;
|
||||||
|
|
||||||
|
public class JMapperIntegrationTest {
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseAnnotation_thenConverted(){
|
||||||
|
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto result = userMapper.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getUsername());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseGlobalMapAnnotation_thenConverted(){
|
||||||
|
JMapper<UserDto1, User> userMapper= new JMapper<>(UserDto1.class, User.class);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto1 result = userMapper.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseAnnotationExplicitConversion_thenConverted(){
|
||||||
|
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto result = userMapper.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getUsername());
|
||||||
|
assertTrue(result.getAge() > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
//======================= XML
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseXml_thenConverted(){
|
||||||
|
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class,"user_jmapper.xml");
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto result = userMapper.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getUsername());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseXmlGlobal_thenConverted(){
|
||||||
|
JMapper<UserDto1, User> userMapper = new JMapper<>(UserDto1.class, User.class,"user_jmapper1.xml");
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto1 result = userMapper.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== API
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseApi_thenConverted(){
|
||||||
|
JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class)
|
||||||
|
.add(attribute("id").value("id"))
|
||||||
|
.add(attribute("username").value("email"))
|
||||||
|
) ;
|
||||||
|
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class, jmapperApi);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto result = userMapper.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getUsername());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseApiGlobal_thenConverted(){
|
||||||
|
JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class)
|
||||||
|
.add(global())
|
||||||
|
) ;
|
||||||
|
JMapper<UserDto1, User> userMapper1 = new JMapper<>(UserDto1.class, User.class,jmapperApi);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto1 result = userMapper1.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getEmail());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,76 @@
|
|||||||
|
package com.baeldung.jmapper;
|
||||||
|
|
||||||
|
import static com.googlecode.jmapper.api.JMapperAPI.attribute;
|
||||||
|
import static com.googlecode.jmapper.api.JMapperAPI.mappedClass;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.jmapper.relational.User;
|
||||||
|
import com.baeldung.jmapper.relational.UserDto1;
|
||||||
|
import com.baeldung.jmapper.relational.UserDto2;
|
||||||
|
import com.googlecode.jmapper.RelationalJMapper;
|
||||||
|
import com.googlecode.jmapper.api.JMapperAPI;
|
||||||
|
|
||||||
|
public class JMapperRelationalIntegrationTest {
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseAnnotation_thenConverted(){
|
||||||
|
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com");
|
||||||
|
UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user);
|
||||||
|
UserDto2 result2= relationalMapper.oneToMany(UserDto2.class, user);
|
||||||
|
|
||||||
|
System.out.println(result1);
|
||||||
|
System.out.println(result2);
|
||||||
|
assertEquals(user.getId(), result1.getId());
|
||||||
|
assertEquals(user.getEmail(), result1.getUsername());
|
||||||
|
assertEquals(user.getId(), result2.getId());
|
||||||
|
assertEquals(user.getEmail(), result2.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
|
//======================= XML
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseXml_thenConverted(){
|
||||||
|
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class,"user_jmapper2.xml");
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com");
|
||||||
|
UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user);
|
||||||
|
UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user);
|
||||||
|
|
||||||
|
System.out.println(result1);
|
||||||
|
System.out.println(result2);
|
||||||
|
assertEquals(user.getId(), result1.getId());
|
||||||
|
assertEquals(user.getEmail(), result1.getUsername());
|
||||||
|
assertEquals(user.getId(), result2.getId());
|
||||||
|
assertEquals(user.getEmail(), result2.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// ===== API
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseApi_thenConverted(){
|
||||||
|
JMapperAPI jmapperApi = new JMapperAPI()
|
||||||
|
.add(mappedClass(User.class)
|
||||||
|
.add(attribute("id").value("id").targetClasses(UserDto1.class,UserDto2.class))
|
||||||
|
.add(attribute("email").targetAttributes("username","email").targetClasses(UserDto1.class,UserDto2.class)) )
|
||||||
|
;
|
||||||
|
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class,jmapperApi);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com");
|
||||||
|
UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user);
|
||||||
|
UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user);
|
||||||
|
|
||||||
|
System.out.println(result1);
|
||||||
|
System.out.println(result2);
|
||||||
|
assertEquals(user.getId(), result1.getId());
|
||||||
|
assertEquals(user.getEmail(), result1.getUsername());
|
||||||
|
assertEquals(user.getId(), result2.getId());
|
||||||
|
assertEquals(user.getEmail(), result2.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -48,8 +48,10 @@
|
|||||||
<exclude>DataTest.java</exclude>
|
<exclude>DataTest.java</exclude>
|
||||||
</excludes>
|
</excludes>
|
||||||
<includes>
|
<includes>
|
||||||
|
<include>TestFail.java</include>
|
||||||
<include>DataCheck.java</include>
|
<include>DataCheck.java</include>
|
||||||
</includes>
|
</includes>
|
||||||
|
<testFailureIgnore>true</testFailureIgnore>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
|
15
maven/src/test/java/testfail/TestFail.java
Normal file
15
maven/src/test/java/testfail/TestFail.java
Normal file
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -2,9 +2,8 @@
|
|||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>cassandra-java-client</artifactId>
|
<artifactId>java-cassandra</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
<name>cassandra-java-client</name>
|
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
|
548
pom.xml
548
pom.xml
@ -195,6 +195,61 @@
|
|||||||
<version>${gitflow-incremental-builder.version}</version>
|
<version>${gitflow-incremental-builder.version}</version>
|
||||||
</extension>
|
</extension>
|
||||||
</extensions>
|
</extensions>
|
||||||
|
<pluginManagement>
|
||||||
|
<plugins>
|
||||||
|
<!--This plugin's configuration is used to store Eclipse m2e settings
|
||||||
|
only. It has no influence on the Maven build itself. -->
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.eclipse.m2e</groupId>
|
||||||
|
<artifactId>lifecycle-mapping</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<configuration>
|
||||||
|
<lifecycleMappingMetadata>
|
||||||
|
<pluginExecutions>
|
||||||
|
<pluginExecution>
|
||||||
|
<pluginExecutionFilter>
|
||||||
|
<groupId>
|
||||||
|
org.commonjava.maven.plugins
|
||||||
|
</groupId>
|
||||||
|
<artifactId>
|
||||||
|
directory-maven-plugin
|
||||||
|
</artifactId>
|
||||||
|
<versionRange>
|
||||||
|
[0.3.1,)
|
||||||
|
</versionRange>
|
||||||
|
<goals>
|
||||||
|
<goal>directory-of</goal>
|
||||||
|
</goals>
|
||||||
|
</pluginExecutionFilter>
|
||||||
|
<action>
|
||||||
|
<ignore></ignore>
|
||||||
|
</action>
|
||||||
|
</pluginExecution>
|
||||||
|
<pluginExecution>
|
||||||
|
<pluginExecutionFilter>
|
||||||
|
<groupId>
|
||||||
|
org.apache.maven.plugins
|
||||||
|
</groupId>
|
||||||
|
<artifactId>
|
||||||
|
maven-install-plugin
|
||||||
|
</artifactId>
|
||||||
|
<versionRange>
|
||||||
|
[2.5.1,)
|
||||||
|
</versionRange>
|
||||||
|
<goals>
|
||||||
|
<goal>install-file</goal>
|
||||||
|
</goals>
|
||||||
|
</pluginExecutionFilter>
|
||||||
|
<action>
|
||||||
|
<ignore></ignore>
|
||||||
|
</action>
|
||||||
|
</pluginExecution>
|
||||||
|
</pluginExecutions>
|
||||||
|
</lifecycleMappingMetadata>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</pluginManagement>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<profiles>
|
<profiles>
|
||||||
@ -203,33 +258,25 @@
|
|||||||
<id>default</id>
|
<id>default</id>
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<executions>
|
<version>${maven-surefire-plugin.version}</version>
|
||||||
<execution>
|
|
||||||
<phase>integration-test</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>test</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
<configuration>
|
||||||
|
<forkCount>3</forkCount>
|
||||||
|
<reuseForks>true</reuseForks>
|
||||||
<excludes>
|
<excludes>
|
||||||
|
<exclude>**/*IntegrationTest.java</exclude>
|
||||||
|
<exclude>**/*IntTest.java</exclude>
|
||||||
|
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||||
<exclude>**/*ManualTest.java</exclude>
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
|
<exclude>**/JdbcTest.java</exclude>
|
||||||
<exclude>**/*LiveTest.java</exclude>
|
<exclude>**/*LiveTest.java</exclude>
|
||||||
</excludes>
|
</excludes>
|
||||||
<includes>
|
|
||||||
<include>**/*IntegrationTest.java</include>
|
|
||||||
<include>**/*IntTest.java</include>
|
|
||||||
</includes>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
<configuration>
|
|
||||||
<systemPropertyVariables>
|
|
||||||
<test.mime>json</test.mime>
|
|
||||||
</systemPropertyVariables>
|
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
@ -499,6 +546,7 @@
|
|||||||
<module>maven-archetype</module>
|
<module>maven-archetype</module>
|
||||||
<module>apache-meecrowave</module>
|
<module>apache-meecrowave</module>
|
||||||
<module>spring-reactive-kotlin</module>
|
<module>spring-reactive-kotlin</module>
|
||||||
|
<module>jnosql</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
</profile>
|
</profile>
|
||||||
@ -572,14 +620,17 @@
|
|||||||
<module>jee-7</module> <module>jhipster/jhipster-monolithic</module> <module>jjwt</module>
|
<module>jee-7</module> <module>jhipster/jhipster-monolithic</module> <module>jjwt</module>
|
||||||
<module>jpa-storedprocedure</module> <module>jsf</module> <module>json-path</module>
|
<module>jpa-storedprocedure</module> <module>jsf</module> <module>json-path</module>
|
||||||
<module>json</module> <module>jsoup</module> <module>testing-modules/junit-5</module>
|
<module>json</module> <module>jsoup</module> <module>testing-modules/junit-5</module>
|
||||||
<module>jws</module> <module>libraries</module> <module>libraries-data</module>
|
<module>jws</module> <module>libraries-data</module> <module>linkrest</module>
|
||||||
<module>linkrest</module> <module>logging-modules/log-mdc</module> <module>logging-modules/log4j</module>
|
<module>logging-modules/log-mdc</module> <module>logging-modules/log4j</module>
|
||||||
<module>logging-modules/log4j2</module> <module>logging-modules/logback</module>
|
<module>logging-modules/log4j2</module> <module>logging-modules/logback</module>
|
||||||
<module>lombok</module> <module>mapstruct</module> <module>metrics</module>
|
<module>lombok</module> <module>mapstruct</module> <module>metrics</module>
|
||||||
<module>maven</module> <module>mesos-marathon</module> <module>msf4j</module> -->
|
<module>maven</module> <module>mesos-marathon</module> <module>msf4j</module> -->
|
||||||
|
|
||||||
<!-- group 1 - OK, 31min, 34 failusres -->
|
<!-- group 1 - OK, 27min, 7911Kb log, 8 failusres -->
|
||||||
|
|
||||||
|
<!-- group 2 -->
|
||||||
|
|
||||||
|
<!-- -->
|
||||||
<module>testing-modules/mockito</module>
|
<module>testing-modules/mockito</module>
|
||||||
<module>testing-modules/mockito-2</module>
|
<module>testing-modules/mockito-2</module>
|
||||||
<module>testing-modules/mocks</module>
|
<module>testing-modules/mocks</module>
|
||||||
@ -615,6 +666,12 @@
|
|||||||
<module>spring-amqp-simple</module>
|
<module>spring-amqp-simple</module>
|
||||||
<module>spring-apache-camel</module>
|
<module>spring-apache-camel</module>
|
||||||
<module>spring-batch</module>
|
<module>spring-batch</module>
|
||||||
|
|
||||||
|
|
||||||
|
<!-- group 2 - Pass, 11-16 min, 42 test failures, 4,020 KB -->
|
||||||
|
|
||||||
|
<!-- group 3.1 -->
|
||||||
|
|
||||||
<module>spring-bom</module>
|
<module>spring-bom</module>
|
||||||
<module>spring-boot</module>
|
<module>spring-boot</module>
|
||||||
<module>spring-boot-keycloak</module>
|
<module>spring-boot-keycloak</module>
|
||||||
@ -640,6 +697,276 @@
|
|||||||
<module>persistence-modules/spring-data-neo4j</module>
|
<module>persistence-modules/spring-data-neo4j</module>
|
||||||
<module>persistence-modules/spring-data-redis</module>
|
<module>persistence-modules/spring-data-redis</module>
|
||||||
<module>spring-data-rest</module>
|
<module>spring-data-rest</module>
|
||||||
|
|
||||||
|
<!-- group 3.1 - Pass, 23 min, 35 failed tests, 7,942 KB -->
|
||||||
|
|
||||||
|
<!-- group 3.2 -->
|
||||||
|
|
||||||
|
<!-- -->
|
||||||
|
<module>persistence-modules/spring-data-solr</module>
|
||||||
|
<module>spring-dispatcher-servlet</module>
|
||||||
|
<module>spring-exceptions</module>
|
||||||
|
<module>spring-freemarker</module>
|
||||||
|
<module>persistence-modules/spring-hibernate-3</module>
|
||||||
|
<module>spring-hibernate4</module>
|
||||||
|
<module>persistence-modules/spring-hibernate-5</module>
|
||||||
|
<module>persistence-modules/spring-data-eclipselink</module>
|
||||||
|
<module>spring-integration</module>
|
||||||
|
<module>spring-jenkins-pipeline</module>
|
||||||
|
<module>spring-jersey</module>
|
||||||
|
<module>spring-jms</module>
|
||||||
|
<module>spring-jooq</module>
|
||||||
|
<module>persistence-modules/spring-jpa</module>
|
||||||
|
<module>spring-kafka</module>
|
||||||
|
<module>spring-katharsis</module>
|
||||||
|
<module>spring-ldap</module>
|
||||||
|
<module>spring-mockito</module>
|
||||||
|
<module>spring-mvc-forms-jsp</module>
|
||||||
|
<module>spring-mvc-forms-thymeleaf</module>
|
||||||
|
<module>spring-mvc-java</module>
|
||||||
|
<module>spring-mvc-velocity</module>
|
||||||
|
<module>spring-mvc-webflow</module>
|
||||||
|
<module>spring-mvc-xml</module>
|
||||||
|
<module>spring-mvc-kotlin</module>
|
||||||
|
<module>spring-protobuf</module>
|
||||||
|
<module>spring-quartz</module>
|
||||||
|
<module>spring-rest-angular</module>
|
||||||
|
<module>spring-rest-full</module>
|
||||||
|
<module>spring-rest-query-language</module>
|
||||||
|
<module>spring-rest</module>
|
||||||
|
<module>spring-rest-simple</module>
|
||||||
|
<module>spring-reactive-kotlin</module>
|
||||||
|
|
||||||
|
|
||||||
|
<!-- group 3.2 - Pass, 8 minutes, 1 failed test, 2,294 KB log -->
|
||||||
|
<!-- group 3 - Pass, 25 minutes, 36 failed tests, 10,163 KB log -->
|
||||||
|
<!-- group 3 - Pass, 23 minutes, 31 failed tests, 8,693 KB log -->
|
||||||
|
<!-- group 2+3 - Fail, 12 minutes, 44 failed tests -->
|
||||||
|
|
||||||
|
<!-- group 4 -->
|
||||||
|
|
||||||
|
<!-- <module>spring-security-acl</module> <module>spring-security-cache-control</module>
|
||||||
|
<module>spring-security-client/spring-security-jsp-authentication</module>
|
||||||
|
<module>spring-security-client/spring-security-jsp-authorize</module> <module>spring-security-client/spring-security-jsp-config</module>
|
||||||
|
<module>spring-security-client/spring-security-mvc</module> <module>spring-security-client/spring-security-thymeleaf-authentication</module>
|
||||||
|
<module>spring-security-client/spring-security-thymeleaf-authorize</module>
|
||||||
|
<module>spring-security-client/spring-security-thymeleaf-config</module>
|
||||||
|
<module>spring-security-core</module> <module>spring-security-mvc-boot</module>
|
||||||
|
<module>spring-security-mvc-custom</module> <module>spring-security-mvc-digest-auth</module>
|
||||||
|
<module>spring-security-mvc-ldap</module> <module>spring-security-mvc-login</module>
|
||||||
|
<module>spring-security-mvc-persisted-remember-me</module> <module>spring-security-mvc-session</module>
|
||||||
|
<module>spring-security-mvc-socket</module> <module>spring-security-openid</module>
|
||||||
|
<module>spring-security-react</module> <module>spring-security-rest-basic-auth</module>
|
||||||
|
<module>spring-security-rest-custom</module> <module>spring-security-rest</module>
|
||||||
|
<module>spring-security-sso</module> <module>spring-security-x509</module>
|
||||||
|
<module>spring-session</module> <module>spring-sleuth</module> <module>spring-social-login</module>
|
||||||
|
<module>spring-spel</module> <module>spring-state-machine</module> <module>spring-thymeleaf</module>
|
||||||
|
<module>spring-userservice</module> <module>spring-zuul</module> <module>spring-reactor</module>
|
||||||
|
<module>spring-vertx</module> <module>spring-jinq</module> <module>spring-rest-embedded-tomcat</module>
|
||||||
|
<module>testing-modules/testing</module> <module>testing-modules/testng</module>
|
||||||
|
<module>video-tutorials</module> <module>xml</module> <module>xmlunit-2</module>
|
||||||
|
<module>struts-2</module> <module>apache-velocity</module> <module>apache-solrj</module>
|
||||||
|
<module>rabbitmq</module> <module>vertx</module> <module>persistence-modules/spring-data-gemfire</module>
|
||||||
|
<module>mybatis</module> <module>spring-drools</module> <module>drools</module>
|
||||||
|
<module>persistence-modules/liquibase</module> <module>spring-boot-property-exp</module>
|
||||||
|
<module>testing-modules/mockserver</module> <module>testing-modules/test-containers</module>
|
||||||
|
<module>undertow</module> <module>vertx-and-rxjava</module> <module>saas</module>
|
||||||
|
<module>deeplearning4j</module> <module>lucene</module> <module>vraptor</module>
|
||||||
|
<module>persistence-modules/java-cockroachdb</module> <module>spring-security-thymeleaf</module>
|
||||||
|
<module>persistence-modules/java-jdbi</module> <module>jersey</module> <module>java-spi</module>
|
||||||
|
<module>performance-tests</module> <module>twilio</module> <module>spring-boot-ctx-fluent</module>
|
||||||
|
<module>java-ee-8-security-api</module> <module>spring-webflux-amqp</module>
|
||||||
|
<module>antlr</module> <module>maven-archetype</module> <module>apache-meecrowave</module> -->
|
||||||
|
|
||||||
|
<!-- group 4 - OK, 12 min, 3,961 KB log, 12 failed tests -->
|
||||||
|
|
||||||
|
<!-- <module>libraries</module> <module>jmeter</module> -->
|
||||||
|
|
||||||
|
</modules>
|
||||||
|
|
||||||
|
</profile>
|
||||||
|
|
||||||
|
<profile>
|
||||||
|
<id>integration-lite</id>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>integration-test</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>test</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
|
<exclude>**/*LiveTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
<includes>
|
||||||
|
<include>**/*IntegrationTest.java</include>
|
||||||
|
<include>**/*IntTest.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<systemPropertyVariables>
|
||||||
|
<test.mime>json</test.mime>
|
||||||
|
</systemPropertyVariables>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<modules>
|
||||||
|
<module>parent-boot-1</module>
|
||||||
|
<module>parent-boot-2</module>
|
||||||
|
<module>parent-spring-4</module>
|
||||||
|
<module>parent-spring-5</module>
|
||||||
|
<module>parent-java</module>
|
||||||
|
|
||||||
|
<module>asm</module>
|
||||||
|
<module>atomix</module>
|
||||||
|
<module>apache-cayenne</module>
|
||||||
|
<module>aws</module>
|
||||||
|
<module>aws-lambda</module>
|
||||||
|
<module>akka-streams</module>
|
||||||
|
<module>algorithms</module>
|
||||||
|
<module>annotations</module>
|
||||||
|
<module>apache-cxf</module>
|
||||||
|
<module>apache-fop</module>
|
||||||
|
<module>apache-poi</module>
|
||||||
|
<module>apache-tika</module>
|
||||||
|
<module>apache-thrift</module>
|
||||||
|
<module>apache-curator</module>
|
||||||
|
<module>apache-zookeeper</module>
|
||||||
|
<module>apache-opennlp</module>
|
||||||
|
<module>autovalue</module>
|
||||||
|
<module>axon</module>
|
||||||
|
<module>azure</module>
|
||||||
|
<module>bootique</module>
|
||||||
|
<module>cdi</module>
|
||||||
|
<!--<module>core-java-9</module> --> <!-- Commented because we have still not upgraded to java 9 -->
|
||||||
|
<module>core-java-collections</module>
|
||||||
|
<module>core-java-io</module>
|
||||||
|
<module>core-java-8</module>
|
||||||
|
<module>core-groovy</module>
|
||||||
|
<module>core-java-concurrency</module>
|
||||||
|
<module>couchbase</module>
|
||||||
|
<module>deltaspike</module>
|
||||||
|
<module>dozer</module>
|
||||||
|
<module>ethereum</module>
|
||||||
|
<module>feign</module>
|
||||||
|
<module>flips</module>
|
||||||
|
<module>testing-modules/groovy-spock</module>
|
||||||
|
<module>google-cloud</module>
|
||||||
|
<module>gson</module>
|
||||||
|
<module>guava</module>
|
||||||
|
<module>guava-modules/guava-18</module>
|
||||||
|
<module>guava-modules/guava-19</module>
|
||||||
|
<module>guava-modules/guava-21</module>
|
||||||
|
<module>guice</module>
|
||||||
|
<module>disruptor</module>
|
||||||
|
<module>spring-static-resources</module>
|
||||||
|
<module>hazelcast</module>
|
||||||
|
<module>hbase</module>
|
||||||
|
<module>httpclient</module>
|
||||||
|
<module>hystrix</module>
|
||||||
|
<module>image-processing</module>
|
||||||
|
<module>immutables</module>
|
||||||
|
<module>influxdb</module>
|
||||||
|
<module>jackson</module>
|
||||||
|
<module>vavr</module>
|
||||||
|
<module>java-lite</module>
|
||||||
|
<module>java-numbers</module>
|
||||||
|
<module>java-rmi</module>
|
||||||
|
<module>java-vavr-stream</module>
|
||||||
|
<module>javax-servlets</module>
|
||||||
|
<module>javaxval</module>
|
||||||
|
<module>jaxb</module>
|
||||||
|
<module>javafx</module>
|
||||||
|
<module>jgroups</module>
|
||||||
|
<module>jee-7</module>
|
||||||
|
<module>jjwt</module>
|
||||||
|
<module>jpa-storedprocedure</module>
|
||||||
|
<module>jsf</module>
|
||||||
|
<module>json-path</module>
|
||||||
|
<module>json</module>
|
||||||
|
<module>jsoup</module>
|
||||||
|
<module>testing-modules/junit-5</module>
|
||||||
|
<module>jws</module>
|
||||||
|
<module>libraries-data</module>
|
||||||
|
<module>linkrest</module>
|
||||||
|
<module>logging-modules/log-mdc</module>
|
||||||
|
<module>logging-modules/log4j</module>
|
||||||
|
<module>logging-modules/log4j2</module>
|
||||||
|
<module>logging-modules/logback</module>
|
||||||
|
<module>lombok</module>
|
||||||
|
<module>mapstruct</module>
|
||||||
|
<module>metrics</module>
|
||||||
|
<module>maven</module>
|
||||||
|
<module>mesos-marathon</module>
|
||||||
|
<module>msf4j</module>
|
||||||
|
<module>testing-modules/mockito</module>
|
||||||
|
<module>testing-modules/mockito-2</module>
|
||||||
|
<module>testing-modules/mocks</module>
|
||||||
|
<module>mustache</module>
|
||||||
|
<module>mvn-wrapper</module>
|
||||||
|
<module>noexception</module>
|
||||||
|
<module>orientdb</module>
|
||||||
|
<module>osgi</module>
|
||||||
|
<module>orika</module>
|
||||||
|
<module>patterns</module>
|
||||||
|
<module>pdf</module>
|
||||||
|
<module>protobuffer</module>
|
||||||
|
<module>persistence-modules/querydsl</module>
|
||||||
|
<module>reactor-core</module>
|
||||||
|
<module>persistence-modules/redis</module>
|
||||||
|
<module>testing-modules/rest-assured</module>
|
||||||
|
<module>testing-modules/rest-testing</module>
|
||||||
|
<module>resteasy</module>
|
||||||
|
<module>rxjava</module>
|
||||||
|
<module>spring-swagger-codegen</module>
|
||||||
|
<module>testing-modules/selenium-junit-testng</module>
|
||||||
|
<module>persistence-modules/solr</module>
|
||||||
|
<module>spark-java</module>
|
||||||
|
<module>spring-4</module>
|
||||||
|
<module>spring-5-reactive</module>
|
||||||
|
<module>spring-5-mvc</module>
|
||||||
|
<module>spring-5-security</module>
|
||||||
|
<module>spring-activiti</module>
|
||||||
|
<module>spring-akka</module>
|
||||||
|
<module>spring-amqp</module>
|
||||||
|
<module>spring-all</module>
|
||||||
|
<module>spring-amqp-simple</module>
|
||||||
|
<module>spring-apache-camel</module>
|
||||||
|
<module>spring-batch</module>
|
||||||
|
<module>spring-bom</module>
|
||||||
|
<module>spring-boot-keycloak</module>
|
||||||
|
<module>spring-boot-bootstrap</module>
|
||||||
|
<module>spring-boot-admin</module>
|
||||||
|
<module>spring-boot-persistence</module>
|
||||||
|
<module>spring-boot-security</module>
|
||||||
|
<module>spring-boot-mvc</module>
|
||||||
|
<module>spring-boot-logging-log4j2</module>
|
||||||
|
<module>spring-cloud-data-flow</module>
|
||||||
|
<module>spring-cloud</module>
|
||||||
|
<module>spring-core</module>
|
||||||
|
<module>spring-cucumber</module>
|
||||||
|
<module>spring-ejb</module>
|
||||||
|
<module>spring-aop</module>
|
||||||
|
<module>persistence-modules/spring-data-cassandra</module>
|
||||||
|
<module>spring-data-couchbase-2</module>
|
||||||
|
<module>persistence-modules/spring-data-dynamodb</module>
|
||||||
|
<module>spring-data-elasticsearch</module>
|
||||||
|
<module>spring-data-keyvalue</module>
|
||||||
|
<module>spring-data-mongodb</module>
|
||||||
|
<module>persistence-modules/spring-data-neo4j</module>
|
||||||
|
<module>persistence-modules/spring-data-redis</module>
|
||||||
|
<module>spring-data-rest</module>
|
||||||
<module>persistence-modules/spring-data-solr</module>
|
<module>persistence-modules/spring-data-solr</module>
|
||||||
<module>spring-dispatcher-servlet</module>
|
<module>spring-dispatcher-servlet</module>
|
||||||
<module>spring-exceptions</module>
|
<module>spring-exceptions</module>
|
||||||
@ -673,46 +1000,161 @@
|
|||||||
<module>spring-rest-query-language</module>
|
<module>spring-rest-query-language</module>
|
||||||
<module>spring-rest</module>
|
<module>spring-rest</module>
|
||||||
<module>spring-rest-simple</module>
|
<module>spring-rest-simple</module>
|
||||||
<module>spring-reactive-kotlin</module>
|
<module>spring-security-acl</module>
|
||||||
|
<module>spring-security-cache-control</module>
|
||||||
<!-- group 2 - ? -->
|
|
||||||
|
|
||||||
<!-- <module>spring-security-acl</module> <module>spring-security-cache-control</module>
|
|
||||||
<module>spring-security-client/spring-security-jsp-authentication</module>
|
<module>spring-security-client/spring-security-jsp-authentication</module>
|
||||||
<module>spring-security-client/spring-security-jsp-authorize</module> <module>spring-security-client/spring-security-jsp-config</module>
|
<module>spring-security-client/spring-security-jsp-authorize</module>
|
||||||
<module>spring-security-client/spring-security-mvc</module> <module>spring-security-client/spring-security-thymeleaf-authentication</module>
|
<module>spring-security-client/spring-security-jsp-config</module>
|
||||||
|
<module>spring-security-client/spring-security-mvc</module>
|
||||||
|
<module>spring-security-client/spring-security-thymeleaf-authentication</module>
|
||||||
<module>spring-security-client/spring-security-thymeleaf-authorize</module>
|
<module>spring-security-client/spring-security-thymeleaf-authorize</module>
|
||||||
<module>spring-security-client/spring-security-thymeleaf-config</module>
|
<module>spring-security-client/spring-security-thymeleaf-config</module>
|
||||||
<module>spring-security-core</module> <module>spring-security-mvc-boot</module>
|
<module>spring-security-core</module>
|
||||||
<module>spring-security-mvc-custom</module> <module>spring-security-mvc-digest-auth</module>
|
<module>spring-security-mvc-boot</module>
|
||||||
<module>spring-security-mvc-ldap</module> <module>spring-security-mvc-login</module>
|
<module>spring-security-mvc-digest-auth</module>
|
||||||
<module>spring-security-mvc-persisted-remember-me</module> <module>spring-security-mvc-session</module>
|
<module>spring-security-mvc-ldap</module>
|
||||||
<module>spring-security-mvc-socket</module> <module>spring-security-openid</module>
|
<module>spring-security-mvc-login</module>
|
||||||
<module>spring-security-react</module> <module>spring-security-rest-basic-auth</module>
|
<module>spring-security-mvc-persisted-remember-me</module>
|
||||||
<module>spring-security-rest-custom</module> <module>spring-security-rest</module>
|
<module>spring-security-mvc-session</module>
|
||||||
<module>spring-security-sso</module> <module>spring-security-x509</module>
|
<module>spring-security-mvc-socket</module>
|
||||||
<module>spring-session</module> <module>spring-sleuth</module> <module>spring-social-login</module>
|
<module>spring-security-openid</module>
|
||||||
<module>spring-spel</module> <module>spring-state-machine</module> <module>spring-thymeleaf</module>
|
<!--<module>spring-security-react</module> -->
|
||||||
<module>spring-userservice</module> <module>spring-zuul</module> <module>spring-reactor</module>
|
<module>spring-security-rest-basic-auth</module>
|
||||||
<module>spring-vertx</module> <module>spring-jinq</module> <module>spring-rest-embedded-tomcat</module>
|
<module>spring-security-rest-custom</module>
|
||||||
<module>testing-modules/testing</module> <module>testing-modules/testng</module>
|
<module>spring-security-rest</module>
|
||||||
<module>video-tutorials</module> <module>xml</module> <module>xmlunit-2</module>
|
<module>spring-security-sso</module>
|
||||||
<module>struts-2</module> <module>apache-velocity</module> <module>apache-solrj</module>
|
<module>spring-security-x509</module>
|
||||||
<module>rabbitmq</module> <module>vertx</module> <module>persistence-modules/spring-data-gemfire</module>
|
<module>spring-session</module>
|
||||||
<module>mybatis</module> <module>spring-drools</module> <module>drools</module>
|
<module>spring-sleuth</module>
|
||||||
<module>persistence-modules/liquibase</module> <module>spring-boot-property-exp</module>
|
<module>spring-social-login</module>
|
||||||
<module>testing-modules/mockserver</module> <module>testing-modules/test-containers</module>
|
<module>spring-spel</module>
|
||||||
<module>undertow</module> <module>vertx-and-rxjava</module> <module>saas</module>
|
<module>spring-state-machine</module>
|
||||||
<module>deeplearning4j</module> <module>lucene</module> <module>vraptor</module>
|
<module>spring-thymeleaf</module>
|
||||||
<module>persistence-modules/java-cockroachdb</module> <module>spring-security-thymeleaf</module>
|
<module>spring-userservice</module>
|
||||||
<module>persistence-modules/java-jdbi</module> <module>jersey</module> <module>java-spi</module>
|
<module>spring-zuul</module>
|
||||||
<module>performance-tests</module> <module>twilio</module> <module>spring-boot-ctx-fluent</module>
|
<module>spring-reactor</module>
|
||||||
<module>java-ee-8-security-api</module> <module>spring-webflux-amqp</module>
|
<module>spring-vertx</module>
|
||||||
<module>antlr</module> <module>maven-archetype</module> <module>apache-meecrowave</module> -->
|
<module>spring-jinq</module>
|
||||||
|
<module>spring-rest-embedded-tomcat</module>
|
||||||
|
<module>testing-modules/testing</module>
|
||||||
|
<module>testing-modules/testng</module>
|
||||||
|
<module>video-tutorials</module>
|
||||||
|
<module>xml</module>
|
||||||
|
<module>xmlunit-2</module>
|
||||||
|
<module>struts-2</module>
|
||||||
|
<module>apache-velocity</module>
|
||||||
|
<module>apache-solrj</module>
|
||||||
|
<module>rabbitmq</module>
|
||||||
|
<module>vertx</module>
|
||||||
|
<module>persistence-modules/spring-data-gemfire</module>
|
||||||
|
<module>mybatis</module>
|
||||||
|
<module>spring-drools</module>
|
||||||
|
<module>drools</module>
|
||||||
|
<module>persistence-modules/liquibase</module>
|
||||||
|
<module>spring-boot-property-exp</module>
|
||||||
|
<module>testing-modules/mockserver</module>
|
||||||
|
<module>testing-modules/test-containers</module>
|
||||||
|
<module>undertow</module>
|
||||||
|
<module>vertx-and-rxjava</module>
|
||||||
|
<module>saas</module>
|
||||||
|
<module>deeplearning4j</module>
|
||||||
|
<module>lucene</module>
|
||||||
|
<module>vraptor</module>
|
||||||
|
<module>persistence-modules/java-cockroachdb</module>
|
||||||
|
<module>spring-security-thymeleaf</module>
|
||||||
|
<module>persistence-modules/java-jdbi</module>
|
||||||
|
<module>jersey</module>
|
||||||
|
<module>java-spi</module>
|
||||||
|
<module>performance-tests</module>
|
||||||
|
<module>twilio</module>
|
||||||
|
<module>spring-boot-ctx-fluent</module>
|
||||||
|
<module>java-ee-8-security-api</module>
|
||||||
|
<module>spring-webflux-amqp</module>
|
||||||
|
<module>antlr</module>
|
||||||
|
<module>maven-archetype</module>
|
||||||
|
<module>apache-meecrowave</module>
|
||||||
|
<module>ejb</module>
|
||||||
|
<module>persistence-modules/java-cassandra</module>
|
||||||
|
|
||||||
|
<!-- heavy -->
|
||||||
|
<!--
|
||||||
|
<module>libraries</module>
|
||||||
|
<module>geotools</module>
|
||||||
|
<module>jhipster/jhipster-monolithic</module>
|
||||||
|
<module>testing-modules/gatling</module>
|
||||||
|
<module>spring-boot</module>
|
||||||
|
<module>spring-boot-ops</module>
|
||||||
|
<module>spring-5</module>
|
||||||
|
<module>core-kotlin</module>
|
||||||
|
<module>core-java</module>
|
||||||
|
<module>google-web-toolkit</module>
|
||||||
|
<module>spring-security-mvc-custom</module>
|
||||||
|
-->
|
||||||
|
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
</profile>
|
</profile>
|
||||||
|
|
||||||
|
<profile>
|
||||||
|
<id>integration-heavy</id>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>integration-test</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>test</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
|
<exclude>**/*LiveTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
<includes>
|
||||||
|
<include>**/*IntegrationTest.java</include>
|
||||||
|
<include>**/*IntTest.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<systemPropertyVariables>
|
||||||
|
<test.mime>json</test.mime>
|
||||||
|
</systemPropertyVariables>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<modules>
|
||||||
|
<module>parent-boot-1</module>
|
||||||
|
<module>parent-boot-2</module>
|
||||||
|
<module>parent-spring-4</module>
|
||||||
|
<module>parent-spring-5</module>
|
||||||
|
<module>parent-java</module>
|
||||||
|
|
||||||
|
<module>libraries</module>
|
||||||
|
<module>geotools</module>
|
||||||
|
<module>jhipster/jhipster-monolithic</module>
|
||||||
|
<module>testing-modules/gatling</module>
|
||||||
|
<module>spring-boot</module>
|
||||||
|
<module>spring-boot-ops</module>
|
||||||
|
<module>spring-5</module>
|
||||||
|
<module>core-kotlin</module>
|
||||||
|
<module>core-java</module>
|
||||||
|
<module>google-web-toolkit</module>
|
||||||
|
<module>spring-security-mvc-custom</module>
|
||||||
|
<module>hibernate5</module>
|
||||||
|
|
||||||
|
</modules>
|
||||||
|
|
||||||
|
</profile>
|
||||||
|
|
||||||
|
|
||||||
</profiles>
|
</profiles>
|
||||||
|
|
||||||
<reporting>
|
<reporting>
|
||||||
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<String> corsDisabledEndpoint() {
|
||||||
|
return Mono.just("Regular endpoint");
|
||||||
|
}
|
||||||
|
|
||||||
|
@CrossOrigin
|
||||||
|
@PutMapping("/cors-enabled-endpoint")
|
||||||
|
public Mono<String> corsEnabledEndpoint() {
|
||||||
|
return Mono.just("CORS enabled endpoint");
|
||||||
|
}
|
||||||
|
|
||||||
|
@CrossOrigin({ "http://another-allowed-origin.com" })
|
||||||
|
@PutMapping("/cors-enabled-origin-restrictive-endpoint")
|
||||||
|
public Mono<String> corsEnabledOriginRestrictiveEndpoint() {
|
||||||
|
return Mono.just("CORS enabled endpoint - Origin Restrictive");
|
||||||
|
}
|
||||||
|
|
||||||
|
@CrossOrigin(allowedHeaders = { "Baeldung-Allowed" })
|
||||||
|
@PutMapping("/cors-enabled-header-restrictive-endpoint")
|
||||||
|
public Mono<String> corsEnabledHeaderRestrictiveEndpoint() {
|
||||||
|
return Mono.just("CORS enabled endpoint - Header Restrictive");
|
||||||
|
}
|
||||||
|
|
||||||
|
@CrossOrigin(exposedHeaders = { "Baeldung-Exposed" })
|
||||||
|
@PutMapping("/cors-enabled-exposed-header-endpoint")
|
||||||
|
public Mono<String> 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<String> corsEnabledHeaderExposedEndpoint() {
|
||||||
|
return Mono.just("CORS enabled endpoint - Mixed Config");
|
||||||
|
}
|
||||||
|
}
|
@ -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<String> corsDisabledEndpoint() {
|
||||||
|
return Mono.just("CORS disabled endpoint");
|
||||||
|
}
|
||||||
|
|
||||||
|
@CrossOrigin
|
||||||
|
@PutMapping("/cors-enabled-endpoint")
|
||||||
|
public Mono<String> corsEnabledEndpoint() {
|
||||||
|
return Mono.just("CORS enabled endpoint");
|
||||||
|
}
|
||||||
|
|
||||||
|
@CrossOrigin({ "http://allowed-origin.com" })
|
||||||
|
@PutMapping("/cors-enabled-origin-restrictive-endpoint")
|
||||||
|
public Mono<String> corsEnabledOriginRestrictiveEndpoint() {
|
||||||
|
return Mono.just("CORS enabled endpoint - Origin Restrictive");
|
||||||
|
}
|
||||||
|
|
||||||
|
@CrossOrigin(allowedHeaders = { "Baeldung-Allowed" })
|
||||||
|
@PutMapping("/cors-enabled-header-restrictive-endpoint")
|
||||||
|
public Mono<String> corsEnabledHeaderRestrictiveEndpoint() {
|
||||||
|
return Mono.just("CORS enabled endpoint - Header Restrictive");
|
||||||
|
}
|
||||||
|
|
||||||
|
@CrossOrigin(exposedHeaders = { "Baeldung-Exposed" })
|
||||||
|
@PutMapping("/cors-enabled-exposed-header-endpoint")
|
||||||
|
public Mono<String> 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<String> corsEnabledHeaderExposedEndpoint() {
|
||||||
|
return Mono.just("CORS enabled endpoint - Mixed Config");
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<String> corsEnabledHeaderExposedEndpoint() {
|
||||||
|
return Mono.just("CORS Global Configured + Request Configs.");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<String> regularPutEndpoint() {
|
||||||
|
return Mono.just("Regular PUT endpoint");
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/regular-delete-endpoint")
|
||||||
|
public Mono<String> regularDeleteEndpoint() {
|
||||||
|
return Mono.just("Regular DELETE endpoint");
|
||||||
|
}
|
||||||
|
}
|
@ -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<ServerResponse> 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);
|
||||||
|
}
|
||||||
|
}
|
@ -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<ServerResponse> responseHeaderRoute(@Autowired FunctionalHandler handler) {
|
||||||
|
return RouterFunctions.route(RequestPredicates.PUT("/global-config-on-functional/cors-disabled-functional-endpoint"), handler::useHandler);
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<String> corsEnabledHeaderExposedEndpoint() {
|
||||||
|
final String responseMessage = "CORS @CrossOrigin IS NOT EFFECTIVE with WebFilter!!!";
|
||||||
|
|
||||||
|
return Mono.just(responseMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<String> regularPutEndpoint() {
|
||||||
|
return Mono.just("Regular PUT endpoint");
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/regular-delete-endpoint")
|
||||||
|
public Mono<String> regularDeleteEndpoint() {
|
||||||
|
return Mono.just("Regular DELETE endpoint");
|
||||||
|
}
|
||||||
|
}
|
@ -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<ServerResponse> useHandler(final ServerRequest request) {
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.body(Mono.just("Functional Endpoint"), String.class);
|
||||||
|
}
|
||||||
|
}
|
@ -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<ServerResponse> responseHeaderRoute(@Autowired CorsWithWebFilterHandler handler) {
|
||||||
|
return RouterFunctions.route(RequestPredicates.PUT("/web-filter-on-functional/functional-endpoint"), handler::useHandler);
|
||||||
|
}
|
||||||
|
}
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
@ -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<Void> 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);
|
|
||||||
}
|
|
||||||
}
|
|
@ -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<Void> 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);
|
|
||||||
}
|
|
||||||
}
|
|
@ -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<String> 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<Library> 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<String> 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<Library> 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<String> 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);
|
|
||||||
}
|
|
||||||
}
|
|
14
spring-rest-template/.gitignore
vendored
Normal file
14
spring-rest-template/.gitignore
vendored
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
*.class
|
||||||
|
|
||||||
|
#folders#
|
||||||
|
/target
|
||||||
|
/neoDb*
|
||||||
|
/data
|
||||||
|
/src/main/webapp/WEB-INF/classes
|
||||||
|
*/META-INF/*
|
||||||
|
*/.idea/*
|
||||||
|
|
||||||
|
# Packaged files #
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.ear
|
4
spring-rest-template/README.md
Normal file
4
spring-rest-template/README.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
## Spring REST Template Example Project
|
||||||
|
|
||||||
|
### The Course
|
||||||
|
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
11
spring-rest-template/checkstyle.xml
Normal file
11
spring-rest-template/checkstyle.xml
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE module PUBLIC
|
||||||
|
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
|
||||||
|
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
|
||||||
|
<module name="Checker">
|
||||||
|
<module name="TreeWalker">
|
||||||
|
<module name="AvoidStarImport">
|
||||||
|
<property name="severity" value="warning" />
|
||||||
|
</module>
|
||||||
|
</module>
|
||||||
|
</module>
|
83
spring-rest-template/pom.xml
Normal file
83
spring-rest-template/pom.xml
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>spring-rest-template</artifactId>
|
||||||
|
<version>0.1-SNAPSHOT</version>
|
||||||
|
<name>spring-rest-template</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<artifactId>parent-boot-2</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../parent-boot-2</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<!-- Spring -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-web</artifactId>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<artifactId>commons-logging</artifactId>
|
||||||
|
<groupId>commons-logging</groupId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>spring-rest-template</finalName>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-checkstyle-plugin</artifactId>
|
||||||
|
<version>${checkstyle-maven-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<configLocation>checkstyle.xml</configLocation>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>check</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<forkCount>3</forkCount>
|
||||||
|
<reuseForks>true</reuseForks>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*IntegrationTest.java</exclude>
|
||||||
|
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||||
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
|
<exclude>**/*LiveTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
<reporting>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-checkstyle-plugin</artifactId>
|
||||||
|
<version>${checkstyle-maven-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<configLocation>checkstyle.xml</configLocation>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</reporting>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- Maven plugins -->
|
||||||
|
<checkstyle-maven-plugin.version>3.0.0</checkstyle-maven-plugin.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
@ -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<String, Object> body = new LinkedMultiValueMap<>();
|
||||||
|
body.add("file", getTestFile());
|
||||||
|
|
||||||
|
|
||||||
|
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
|
||||||
|
String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/";
|
||||||
|
RestTemplate restTemplate = new RestTemplate();
|
||||||
|
ResponseEntity<String> 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<String, Object> body = new LinkedMultiValueMap<>();
|
||||||
|
body.add("files", getTestFile());
|
||||||
|
body.add("files", getTestFile());
|
||||||
|
body.add("files", getTestFile());
|
||||||
|
|
||||||
|
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
|
||||||
|
String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/";
|
||||||
|
RestTemplate restTemplate = new RestTemplate();
|
||||||
|
ResponseEntity<String> 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());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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<String> 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<String> 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<String> 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<String> response = restTemplate.getForEntity(base.toString()+"/user", String.class);
|
|
||||||
|
|
||||||
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
|
|
||||||
assertTrue(response
|
|
||||||
.getBody()
|
|
||||||
.contains("Unauthorized"));
|
|
||||||
}
|
|
||||||
}
|
|
@ -3,7 +3,6 @@ package org.baeldung.security.spring;
|
|||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
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.authentication.builders.AuthenticationManagerBuilder;
|
||||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
@ -24,7 +23,7 @@ public class ManualSecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
|
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
|
@Override
|
||||||
@ -32,7 +31,7 @@ public class ManualSecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
web.ignoring().antMatchers("/resources/**");
|
web.ignoring().antMatchers("/resources/**");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
|
@Bean("authenticationManager")
|
||||||
@Override
|
@Override
|
||||||
public AuthenticationManager authenticationManagerBean() throws Exception {
|
public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||||
return super.authenticationManagerBean();
|
return super.authenticationManagerBean();
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
package org.baeldung.security.spring;
|
package org.baeldung.security.spring;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
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.authentication.builders.AuthenticationManagerBuilder;
|
||||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
@ -17,7 +19,11 @@ public class SecurityWithCsrfConfig extends WebSecurityConfigurerAdapter {
|
|||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
// java config
|
@Bean("authenticationManager")
|
||||||
|
@Override
|
||||||
|
public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||||
|
return super.authenticationManagerBean();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
|
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user