This commit is contained in:
DOHA 2018-07-21 14:46:16 +03:00
commit 7d2adf29b3
239 changed files with 7066 additions and 1657 deletions

View File

@ -4,7 +4,7 @@ before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: skip
script: travis_wait 60 mvn -q install
script: travis_wait 60 mvn -q install -Pdefault
sudo: required

View File

@ -19,7 +19,7 @@ In additional to Spring, the following technologies are in focus: `core Java`, `
Building the project
====================
To do the full build, do: `mvn install -Dgib.enabled=false`
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
Working with the code in Eclipse

88
apache-avro/pom.xml Normal file
View 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>

View File

@ -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"));
}
}

View File

@ -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;
}
}

View File

@ -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$; }
}

View File

@ -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));
}
}

View File

@ -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));
}
}

View File

@ -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;
}
}
}

View File

@ -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;
}
}

View 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"
]
}
}
]
}

View File

@ -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()));
}
}

View File

@ -52,16 +52,21 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<main.class>com.baeldung.bootique.App</main.class>
<bootique-bom.version>0.23</bootique-bom.version>
<maven-shade-plugin.version>2.4.3</maven-shade-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.java10.list;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
public class CopyListServiceUnitTest {
@Test(expected = UnsupportedOperationException.class)
public void whenModifyCopyOfList_thenThrowsException() {
List<Integer> copyList = List.copyOf(Arrays.asList(1, 2, 3, 4));
}
}

View File

@ -128,77 +128,6 @@
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.list;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CopyListService {
public List<Flower> copyListByConstructor(List<Flower> source) {
return new ArrayList<Flower>(source);
}
public List<Flower> copyListByConstructorAndEditOneFlowerInTheNewList(List<Flower> source) {
List<Flower> flowers = new ArrayList<>(source);
if(flowers.size() > 0) {
flowers.get(0).setPetals(flowers.get(0).getPetals() * 3);
}
return flowers;
}
public List<Flower> copyListByAddAllMethod(List<Flower> source) {
List<Flower> flowers = new ArrayList<>();
flowers.addAll(source);
return flowers;
}
public List<Flower> copyListByAddAllMethodAndEditOneFlowerInTheNewList(List<Flower> source) {
List<Flower> flowers = new ArrayList<>();
flowers.addAll(source);
if(flowers.size() > 0) {
flowers.get(0).setPetals(flowers.get(0).getPetals() * 3);
}
return flowers;
}
public List<Integer> copyListByCopyMethod(List<Integer> source, List<Integer> dest) {
Collections.copy(dest, source);
return dest;
}
public List<Flower> copyListByStream(List<Flower> source) {
return source.stream().collect(Collectors.toList());
}
public List<Flower> copyListByStreamAndSkipFirstElement(List<Flower> source) {
return source.stream().skip(1).collect(Collectors.toList());
}
public List<Flower> copyListByStreamWithFilter(List<Flower> source, Integer moreThanPetals) {
return source.stream().filter(f -> f.getPetals() > moreThanPetals).collect(Collectors.toList());
}
public List<Flower> copyListByStreamWithOptional(List<Flower> source) {
return Optional.ofNullable(source)
.map(List::stream)
.orElseGet(Stream::empty)
.collect(Collectors.toList());
}
public List<Flower> copyListByStreamWithOptionalAndSkip(List<Flower> source) {
return Optional.ofNullable(source)
.map(List::stream)
.orElseGet(Stream::empty)
.skip(1)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.list;
public class Flower {
private String name;
private int petals;
public Flower(String name, int petals) {
this.name = name;
this.petals = petals;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPetals() {
return petals;
}
public void setPetals(int petals) {
this.petals = petals;
}
}

View File

@ -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()));
}
}

View File

@ -0,0 +1,129 @@
package com.baeldung.list;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class CopyListServiceUnitTest {
List<Flower> flowers;
private CopyListService copyListService;
@Before
public void init() {
this.copyListService = new CopyListService();
this.flowers = new ArrayList<>();
Flower poppy = new Flower("Poppy", 12);
flowers.add(poppy);
Flower anemone = new Flower("Anemone", 8);
flowers.add(anemone);
Flower catmint = new Flower("Catmint", 12);
flowers.add(catmint);
Flower diascia = new Flower("Diascia", 5);
flowers.add(diascia);
Flower iris = new Flower("Iris", 3);
flowers.add(iris);
Flower pansy = new Flower("Pansy", 5);
flowers.add(pansy);
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByConstructor() {
List<Flower> copy = copyListService.copyListByConstructor(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByConstructor() {
List<Flower> copy = copyListService.copyListByConstructorAndEditOneFlowerInTheNewList(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByAddAllmethod() {
List<Flower> copy = copyListService.copyListByAddAllMethod(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByAddAllmethod() {
List<Flower> copy = copyListService.copyListByAddAllMethodAndEditOneFlowerInTheNewList(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListsHaveSameSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() {
List<Integer> source = Arrays.asList(1,2,3);
List<Integer> dest = Arrays.asList(4,5,6);
dest = copyListService.copyListByCopyMethod(source, dest);
assertEquals(dest.size(), source.size());
assertTrue(dest.containsAll(source));
}
@Test
public void givenAList_whenListsHaveDifferentSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() {
List<Integer> source = Arrays.asList(1,2,3);
List<Integer> dest = Arrays.asList(5,6,7,8,9,10);
dest = copyListService.copyListByCopyMethod(source, dest);
assertNotEquals(dest.size(), source.size());
assertTrue(dest.containsAll(source));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByStreamProcess() {
List<Flower> copy = copyListService.copyListByStream(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneElementLessByStreamProcess() {
List<Flower> copy = copyListService.copyListByStreamAndSkipFirstElement(flowers);
assertNotEquals(copy.size(), flowers.size());
assertEquals(copy.size() + 1, flowers.size());
assertFalse(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithFilterElementsByStreamProcess() {
List<Flower> copy = copyListService.copyListByStreamWithFilter(flowers, 5);
assertNotEquals(copy.size(), flowers.size());
assertEquals(copy.size() + 3, flowers.size());
assertFalse(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListIsNull_thenReturnEmptyListByStreamProcess() {
List<Flower> copy = copyListService.copyListByStreamWithOptional(null);
assertNotNull(copy);
assertEquals(copy.size(), 0);
}
@Test
public void givenAList_whenListIsNotNull_thenReturnAnotherListWithTheElementsByStreamProcess() {
List<Flower> copy = copyListService.copyListByStreamWithOptional(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListIsNotNull_thenReturnAnotherListWithOneElementLessByStreamProcess() {
List<Flower> copy = copyListService.copyListByStreamWithOptionalAndSkip(flowers);
assertNotEquals(copy.size(), flowers.size());
assertEquals(copy.size() + 1, flowers.size());
assertFalse(copy.containsAll(flowers));
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.java.set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class HashSetInitalizingUnitTest {
@Test
public void whenUsingJava_usingArraysStaticMethod_thenCorrectSize() {
Set<String> set = new HashSet<>(Arrays.asList("a", "b", "c"));
assertEquals(3, set.size());
}
@Test
public void whenUsingJava_usingAnonymousClass_thenCorrectSize() {
Set<String> set = new HashSet<String>(){{
add("a");
add("b");
add("c");
}};
assertEquals(3, set.size());
}
@Test
public void whenUsingJava_creatingSingletonSet_thenCorrectSize() {
Set<String> set = Collections.singleton("a");
assertEquals(1, set.size());
}
public static final <T> Set<T> newHashSet(T... objs) {
Set<T> set = new HashSet<T>();
Collections.addAll(set, objs);
return set;
}
@Test
public void whenUsingJava_usingCustomStaticUtilMethod_thenCorrectSize() {
Set<String> set = newHashSet("a","b","c");
assertEquals(3, set.size());
}
@Test
public void whenUsingJava8_usingCollectOnStream_thenCorrectSize() {
Set<String> set = Stream.of("a", "b", "c").collect(Collectors.toCollection(HashSet::new));
assertEquals(3, set.size());
}
@Test
public void whenUsingGoogleGuava_createMutableSet_thenCorrectSize() {
Set<String> set = Sets.newHashSet("a", "b", "c");
assertEquals(3, set.size());
}
@Test
public void whenUsingGoogleGuava_createImmutableSet_thenCorrectSize() {
Set<String> set = ImmutableSet.of("a", "b", "c");
assertEquals(3, set.size());
}
}

View File

@ -75,92 +75,7 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

View File

@ -185,6 +185,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
@ -195,79 +196,6 @@
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
@ -368,6 +296,7 @@
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<spring-web.version>4.3.4.RELEASE</spring-web.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
@ -376,7 +305,7 @@
<!-- maven plugins -->
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<sun-tools.version>1.8.0</sun-tools.version>
<spring-web.version>4.3.4.RELEASE</spring-web.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
</properties>
</project>

View File

@ -73,9 +73,10 @@
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
@ -146,6 +147,21 @@
<artifactId>icu4j</artifactId>
<version>${icu4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>${HikariCP.version}</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
</dependencies>
<build>
@ -348,6 +364,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<executions>
<execution>
<id>run-benchmarks</id>
@ -375,6 +392,7 @@
</profiles>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<gson.version>2.8.2</gson.version>
@ -395,16 +413,23 @@
<vavr.version>0.9.0</vavr.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<assertj-core.version>3.10.0</assertj-core.version>
<!-- JDBC pooling frameworks -->
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
<HikariCP.version>3.2.0</HikariCP.version>
<c3p0.version>0.9.5.2</c3p0.version>
<!-- maven plugins -->
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
<springframework.boot.spring-boot-starter.version>1.5.8.RELEASE</springframework.boot.spring-boot-starter.version>
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<h2database.version>1.4.197</h2database.version>
<esapi.version>2.1.0.1</esapi.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<javax.mail.version>1.5.0-b01</javax.mail.version>
@ -412,6 +437,7 @@
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
<icu4j.version>61.1</icu4j.version>
</properties>

View File

@ -0,0 +1,87 @@
package com.baeldung.connectionpool.connectionpools;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BasicConnectionPool implements ConnectionPool {
private final String url;
private final String user;
private final String password;
private final List<Connection> connectionPool;
private final List<Connection> usedConnections = new ArrayList<>();
private static final int INITIAL_POOL_SIZE = 10;
private final int MAX_POOL_SIZE = 20;
public static BasicConnectionPool create(String url, String user, String password) throws SQLException {
List<Connection> pool = new ArrayList<>(INITIAL_POOL_SIZE);
for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
pool.add(createConnection(url, user, password));
}
return new BasicConnectionPool(url, user, password, pool);
}
private BasicConnectionPool(String url, String user, String password, List<Connection> connectionPool) {
this.url = url;
this.user = user;
this.password = password;
this.connectionPool = connectionPool;
}
@Override
public Connection getConnection() throws SQLException {
if (connectionPool.size() == 0) {
if (usedConnections.size() < MAX_POOL_SIZE) {
connectionPool.add(createConnection(url, user, password));
} else {
throw new RuntimeException("Maximum pool size reached, no available connections!");
}
}
Connection connection = connectionPool.remove(connectionPool.size() - 1);
usedConnections.add(connection);
return connection;
}
@Override
public boolean releaseConnection(Connection connection) {
connectionPool.add(connection);
return usedConnections.remove(connection);
}
private static Connection createConnection(String url, String user, String password) throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public int getSize() {
return connectionPool.size() + usedConnections.size();
}
@Override
public String getUrl() {
return url;
}
@Override
public String getUser() {
return user;
}
@Override
public String getPassword() {
return password;
}
public void shutdown() throws SQLException {
for (Connection c : usedConnections) {
this.releaseConnection(c);
}
for (Connection c : connectionPool) {
c.close();
}
connectionPool.clear();
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.connectionpool.connectionpools;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
public class C3poDataSource {
private static final ComboPooledDataSource cpds = new ComboPooledDataSource();
static {
try {
cpds.setDriverClass("org.h2.Driver");
cpds.setJdbcUrl("jdbc:h2:mem:test");
cpds.setUser("user");
cpds.setPassword("password");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return cpds.getConnection();
}
private C3poDataSource(){}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.connectionpool.connectionpools;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public interface ConnectionPool {
Connection getConnection() throws SQLException;
boolean releaseConnection(Connection connection);
String getUrl();
String getUser();
String getPassword();
}

View File

@ -0,0 +1,25 @@
package com.baeldung.connectionpool.connectionpools;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp2.BasicDataSource;
public class DBCPDataSource {
private static final BasicDataSource ds = new BasicDataSource();
static {
ds.setUrl("jdbc:h2:mem:test");
ds.setUsername("user");
ds.setPassword("password");
ds.setMinIdle(5);
ds.setMaxIdle(10);
ds.setMaxOpenPreparedStatements(100);
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
private DBCPDataSource(){}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.connectionpool.connectionpools;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class HikariCPDataSource {
private static final HikariConfig config = new HikariConfig();
private static final HikariDataSource ds;
static {
config.setJdbcUrl("jdbc:h2:mem:test");
config.setUsername("user");
config.setPassword("password");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds = new HikariDataSource(config);
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
private HikariCPDataSource(){}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.connectionpool;
import com.baeldung.connectionpool.connectionpools.BasicConnectionPool;
import com.baeldung.connectionpool.connectionpools.ConnectionPool;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.BeforeClass;
import org.junit.Test;
public class BasicConnectionPoolUnitTest {
private static ConnectionPool connectionPool;
@BeforeClass
public static void setUpBasicConnectionPoolInstance() throws SQLException {
connectionPool = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledgetConnection_thenCorrect() throws Exception {
assertTrue(connectionPool.getConnection().isValid(1));
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledreleaseConnection_thenCorrect() throws Exception {
Connection connection = connectionPool.getConnection();
assertThat(connectionPool.releaseConnection(connection)).isTrue();
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledgetUrl_thenCorrect() {
assertThat(connectionPool.getUrl()).isEqualTo("jdbc:h2:mem:test");
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledgetUser_thenCorrect() {
assertThat(connectionPool.getUser()).isEqualTo("user");
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledgetPassword_thenCorrect() {
assertThat(connectionPool.getPassword()).isEqualTo("password");
}
@Test(expected = RuntimeException.class)
public void givenBasicConnectionPoolInstance_whenAskedForMoreThanMax_thenError() throws Exception {
// this test needs to be independent so it doesn't share the same connection pool as other tests
ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
final int MAX_POOL_SIZE = 20;
for (int i = 0; i < MAX_POOL_SIZE + 1; i++) {
cp.getConnection();
}
fail();
}
@Test
public void givenBasicConnectionPoolInstance_whenSutdown_thenEmpty() throws Exception {
ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(10);
((BasicConnectionPool) cp).shutdown();
assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(0);
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.connectionpool;
import com.baeldung.connectionpool.connectionpools.C3poDataSource;
import java.sql.SQLException;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class C3poDataSourceUnitTest {
@Test
public void givenC3poDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
assertTrue(C3poDataSource.getConnection().isValid(1));
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.connectionpool;
import com.baeldung.connectionpool.connectionpools.DBCPDataSource;
import java.sql.SQLException;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class DBCPDataSourceUnitTest {
@Test
public void givenDBCPDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
assertTrue(DBCPDataSource.getConnection().isValid(1));
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.connectionpool;
import com.baeldung.connectionpool.connectionpools.HikariCPDataSource;
import java.sql.SQLException;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class HikariCPDataSourceUnitTest {
@Test
public void givenHikariDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
assertTrue(HikariCPDataSource.getConnection().isValid(1));
}
}

View File

@ -60,7 +60,6 @@
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>${kotlin-reflect.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
@ -224,10 +223,11 @@
</build>
<properties>
<kotlin-maven-plugin.version>1.2.41</kotlin-maven-plugin.version>
<kotlin-test-junit.version>1.2.41</kotlin-test-junit.version>
<kotlin-stdlib.version>1.2.41</kotlin-stdlib.version>
<kotlin-reflect.version>1.2.41</kotlin-reflect.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<kotlin-maven-plugin.version>1.2.51</kotlin-maven-plugin.version>
<kotlin-test-junit.version>1.2.51</kotlin-test-junit.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>
<ktor.io.version>0.9.2</ktor.io.version>
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>

View File

@ -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"
}
}

View File

@ -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")
}

View File

@ -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")
}

View File

@ -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))
}

View File

@ -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")
}

View File

@ -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
}

View File

@ -55,6 +55,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
@ -91,6 +92,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<executions>
<execution>
<goals>
@ -133,6 +135,9 @@
<!-- testing -->
<testng.version>6.10</testng.version>
<assertj.version>3.6.1</assertj.version>
<maven-shade-plugin.version>2.4.3</maven-shade-plugin.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
</properties>
</project>

View File

@ -74,7 +74,7 @@
<port>9990</port>
<username>testUser</username>
<password>admin1234!</password>
<filename>${build.finalName}.jar</filename>
<filename>${project.build.finalName}.jar</filename>
</configuration>
</plugin>
</plugins>

View File

@ -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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>geotools</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
@ -58,4 +58,5 @@
<geotools-swing.version>15.2</geotools-swing.version>
<geotools-shapefile.version>15.2</geotools-shapefile.version>
</properties>
</project>

View File

@ -1,27 +1,14 @@
<?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"
<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/maven-v4_0_0.xsd">
<!-- POM file generated with GWT webAppCreator -->
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>google_web_toolkit</artifactId>
<artifactId>google-web-toolkit</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>com.baeldung.Google_web_toolkit</name>
<properties>
<!-- Setting maven.compiler.source to something different to 1.8
needs that you configure the sourceLevel in gwt-maven-plugin since
GWT compiler 2.8 requires 1.8 (see gwt-maven-plugin block below) -->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- Don't let your Mac use a crazy non-standard encoding -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencyManagement>
<dependencies>
@ -61,12 +48,13 @@
</dependencies>
<build>
<!-- Output classes directly into the webapp, so that IDEs and "mvn process-classes" update them in DevMode -->
<!-- Output classes directly into the webapp, so that IDEs and "mvn process-classes"
update them in DevMode -->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
<plugins>
<!-- GWT Maven Plugin-->
<!-- GWT Maven Plugin -->
<plugin>
<groupId>net.ltgt.gwt.maven</groupId>
<artifactId>gwt-maven-plugin</artifactId>
@ -83,8 +71,8 @@
<moduleName>com.baeldung.Google_web_toolkit</moduleName>
<moduleShortName>Google_web_toolkit</moduleShortName>
<failOnError>true</failOnError>
<!-- GWT compiler 2.8 requires 1.8, hence define sourceLevel here if you use
a different source language for java compilation -->
<!-- GWT compiler 2.8 requires 1.8, hence define sourceLevel here if
you use a different source language for java compilation -->
<sourceLevel>1.8</sourceLevel>
<!-- Compiler configuration -->
<compilerArgs>
@ -113,4 +101,18 @@
</plugins>
</build>
<properties>
<!-- Setting maven.compiler.source to something different to 1.8 needs
that you configure the sourceLevel in gwt-maven-plugin since GWT compiler
2.8 requires 1.8 (see gwt-maven-plugin block below) -->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- Don't let your Mac use a crazy non-standard encoding -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
</project>

View File

@ -5,8 +5,6 @@
<groupId>com.baeldung</groupId>
<artifactId>hibernate5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hibernate5</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
@ -59,9 +57,6 @@
</build>
<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>
<mysql.version>6.0.6</mysql.version>
<mariaDB4j.version>2.2.3</mariaDB4j.version>

View 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>

View File

@ -3,32 +3,27 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>java-ee-8-security-api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>app-auth-basic-store-db</module>
<module>app-auth-form-store-ldap</module>
<module>app-auth-custom-form-store-custom</module>
<module>app-auth-custom-no-store</module>
</modules>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>${javaee-version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<packagingExcludes>pom.xml</packagingExcludes>
@ -69,6 +64,15 @@
<liberty-maven-plugin.version>2.3</liberty-maven-plugin.version>
<openliberty-runtime.version>18.0.0.1</openliberty-runtime.version>
<h2-version>1.4.197</h2-version>
<maven-war-plugin.version>3.2.2</maven-war-plugin.version>
</properties>
<modules>
<module>app-auth-basic-store-db</module>
<module>app-auth-form-store-ldap</module>
<module>app-auth-custom-form-store-custom</module>
<module>app-auth-custom-no-store</module>
</modules>
</project>

View File

@ -100,102 +100,6 @@
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<version>${onejar-maven-plugin.version}</version>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<configuration>
<executable>java</executable>
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
@ -235,31 +139,6 @@
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
@ -280,7 +159,5 @@
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
</properties>
</project>

View File

@ -6,7 +6,7 @@
<artifactId>jhipster-monolithic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>JHipster Monolithic Application</name>
<description>JHipster Monolithic Application</description>
<parent>
<artifactId>parent-boot-1</artifactId>

View File

@ -3,28 +3,9 @@
<configuration scan="true">
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<!-- The FILE and ASYNC appenders are here as examples for a production configuration -->
<!--
<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>
<logger name="com.baeldung" level="INFO"/>
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>512</queueSize>
<appender-ref ref="FILE"/>
</appender>
-->
<logger name="com.baeldung" level="#logback.loglevel#"/>
<logger name="io.github.jhipster" level="DEBUG"/>
<logger name="io.github.jhipster" level="INFO"/>
<logger name="javax.activation" level="WARN"/>
<logger name="javax.mail" level="WARN"/>

View File

@ -33,6 +33,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
@ -46,6 +47,7 @@
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
</properties>
</project>

View 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>

View File

@ -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 {
}

View File

@ -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 !");
}
}

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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);
}

View File

@ -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();
}

View File

@ -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();
}
}

View File

@ -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 {
}

View File

@ -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 {
}

View 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>

View File

@ -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>

View 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"
}
}
]

View 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"
}
}
]

View 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>

View File

@ -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();
}
}

View File

@ -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);
}
}
}

View File

@ -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();
}
}

View File

@ -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 +
'}';
}
}

View File

@ -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();
}
}

View File

@ -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);

View File

@ -0,0 +1 @@
hazelcast-instanceName=hazelcast

View File

@ -0,0 +1,2 @@
#Define Host and Port
mongodb-server-host-1=localhost:27017

23
jnosql/pom.xml Normal file
View 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>

View File

@ -44,6 +44,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
</plugin>
</plugins>
</build>
@ -52,6 +53,8 @@
<jooby.version>1.1.3</jooby.version>
<application.class>com.baeldung.jooby.App</application.class>
<jooby-jedis.version>1.1.3</jooby-jedis.version>
<maven-shade-plugin.version>2.4.3</maven-shade-plugin.version>
</properties>
</project>

View File

@ -1,2 +0,0 @@
## Relevant articles:
- [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order)

View File

@ -31,7 +31,7 @@ import org.springframework.web.client.RestTemplate;
import io.specto.hoverfly.junit.core.SimulationSource;
import io.specto.hoverfly.junit.rule.HoverflyRule;
public class HoverflyApiIntegrationTest {
public class HoverflyApiLiveTest {
private static final SimulationSource source = dsl(service("http://www.baeldung.com").get("/api/courses/1").willReturn(success().body(jsonWithSingleQuotes("{'id':'1','name':'HCI'}")))

View File

@ -5,7 +5,7 @@ import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class HelloWorldServiceIntegrationTest extends AbstractIntegrationTest {
public class HelloWorldServiceTemporaryLiveTest extends AbstractIntegrationTest {
@Test
public void whenGetIsCalledTwoTimes_thenTheSecondShouldHitTheCache() {

View File

@ -17,7 +17,7 @@ public class JMapperIntegrationTest {
@Test
public void giventUser_whenUseAnnotation_thenConverted(){
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));
@ -29,7 +29,7 @@ public class JMapperIntegrationTest {
}
@Test
public void giventUser_whenUseGlobalMapAnnotation_thenConverted(){
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));
@ -41,7 +41,7 @@ public class JMapperIntegrationTest {
}
@Test
public void giventUser_whenUseAnnotationExplicitConversion_thenConverted(){
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));
@ -56,7 +56,7 @@ public class JMapperIntegrationTest {
//======================= XML
@Test
public void giventUser_whenUseXml_thenConverted(){
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));
@ -68,7 +68,7 @@ public class JMapperIntegrationTest {
}
@Test
public void giventUser_whenUseXmlGlobal_thenConverted(){
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));
@ -82,7 +82,7 @@ public class JMapperIntegrationTest {
// ===== API
@Test
public void giventUser_whenUseApi_thenConverted(){
public void givenUser_whenUseApi_thenConverted(){
JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class)
.add(attribute("id").value("id"))
.add(attribute("username").value("email"))
@ -98,7 +98,7 @@ public class JMapperIntegrationTest {
}
@Test
public void giventUser_whenUseApiGlobal_thenConverted(){
public void givenUser_whenUseApiGlobal_thenConverted(){
JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class)
.add(global())
) ;

View File

@ -16,7 +16,7 @@ public class JMapperRelationalIntegrationTest {
@Test
public void giventUser_whenUseAnnotation_thenConverted(){
public void givenUser_whenUseAnnotation_thenConverted(){
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class);
User user = new User(1L,"john@test.com");
@ -34,7 +34,7 @@ public class JMapperRelationalIntegrationTest {
//======================= XML
@Test
public void giventUser_whenUseXml_thenConverted(){
public void givenUser_whenUseXml_thenConverted(){
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class,"user_jmapper2.xml");
User user = new User(1L,"john@test.com");
@ -53,7 +53,7 @@ public class JMapperRelationalIntegrationTest {
// ===== API
@Test
public void giventUser_whenUseApi_thenConverted(){
public void givenUser_whenUseApi_thenConverted(){
JMapperAPI jmapperApi = new JMapperAPI()
.add(mappedClass(User.class)
.add(attribute("id").value("id").targetClasses(UserDto1.class,UserDto2.class))

View File

@ -48,8 +48,10 @@
<exclude>DataTest.java</exclude>
</excludes>
<includes>
<include>TestFail.java</include>
<include>DataCheck.java</include>
</includes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>

View 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);
}
}

View File

@ -106,5 +106,4 @@ public class MavenWrapperDownloader {
fos.close();
rbc.close();
}
}

Some files were not shown because too many files have changed in this diff Show More