This commit is contained in:
Krzysztof Majewski 2018-08-10 09:30:51 +02:00
commit 83cba874f2
1033 changed files with 33903 additions and 2374 deletions

14
.gitignore vendored
View File

@ -48,3 +48,17 @@ dependency-reduced-pom.xml
*.so
*.dylib
*.dll
xml/src/test/resources/example_dom4j_new.xml
xml/src/test/resources/example_dom4j_updated.xml
xml/src/test/resources/example_jaxb_new.xml
core-java-io/hard_link.txt
core-java-io/target_link.txt
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
ethereum/logs/
jmeter/src/main/resources/*-JMeter.csv
**/node_modules/
**/dist
**/tmp
**/out-tsc

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -23,3 +23,4 @@
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

2
apache-avro/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Guide to Apache Avro](http://www.baeldung.com/java-apache-avro)

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,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,3 @@
### Relevant Articles:
================================
- [Building a Microservice with Apache Meecrowave](http://www.baeldung.com/apache-meecrowave)

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -8,9 +8,10 @@
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-1</relativePath>
</parent>
<dependencies>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -10,10 +10,10 @@
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.13.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
<artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-1</relativePath>
</parent>
<dependencies>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -3,3 +3,4 @@
- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference)
- [Guide to Java 10](http://www.baeldung.com/java-10-overview)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -46,7 +46,6 @@
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
- [Java Optional orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
@ -55,3 +54,9 @@
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)

View File

@ -99,6 +99,16 @@
<artifactId>joda-time</artifactId>
<version>${joda.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${asspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${asspectj.version}</version>
</dependency>
</dependencies>
<build>
@ -170,6 +180,7 @@
<joda.version>2.10</joda.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<asspectj.version>1.8.9</asspectj.version>
<avaitility.version>1.7.0</avaitility.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version>

View File

@ -0,0 +1,9 @@
package com.baeldung.aspect;
public aspect ChangeCallsToCurrentTimeInMillisMethod {
long around():
call(public static native long java.lang.System.currentTimeMillis())
&& within(user.code.base.pckg.*) {
return 0;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull {
/**
* This method shows how to make a null safe stream from a collection through the use of
* emptyIfNull() method from Apache Commons CollectionUtils library
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return emptyIfNull(collection).stream();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingJava8OptionalContainer {
/**
* This method shows how to make a null safe stream from a collection through the use of
* Java SE 8s Optional Container
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return Optional.ofNullable(collection)
.map(Collection::stream)
.orElseGet(Stream::empty);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingNullDereferenceCheck {
/**
* This method shows how to make a null safe stream from a collection through the use of a check
* to prevent null dereferences
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return collection == null ? Stream.empty() : collection.stream();
}
}

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,72 @@
package com.baeldung.datetime;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Assert;
import org.junit.Test;
public class UseTimeZoneUnitTest {
/* https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */
String timeZone = "Asia/Singapore";
private static final String PATTERN = "E yyyy-MM-dd HH:mm:ss a";
@Test
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava7_ThenTimeZoneIsSetSuccessfully() {
Date nowUtc = new Date();
TimeZone asiaSingapore = TimeZone.getTimeZone(timeZone);
Calendar nowAsiaSingapore = Calendar.getInstance(asiaSingapore);
nowAsiaSingapore.setTime(nowUtc);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
System.out.println(String.format("Java7: Time now in '%s' is '%s'", nowAsiaSingapore.getTimeZone()
.getID(), simpleDateFormat.format(nowAsiaSingapore.getTime())));
Assert.assertEquals(nowUtc.toInstant().getEpochSecond(), nowAsiaSingapore.toInstant().getEpochSecond());
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getTimeZone());
}
@Test
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava8_ThenTimeZoneIsSetSuccessfully() {
Instant nowUtc = Instant.now();
ZoneId asiaSingapore = ZoneId.of(timeZone);
ZonedDateTime nowAsiaSingapore = ZonedDateTime.ofInstant(nowUtc, asiaSingapore);
System.out.println(String.format("Java8: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(),
nowAsiaSingapore.format(DateTimeFormatter.ofPattern(PATTERN))));
Assert.assertEquals(nowUtc.getEpochSecond(), nowAsiaSingapore.toEpochSecond());
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone());
}
@Test
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJodaTime_ThenTimeZoneIsSetSuccessfully() {
org.joda.time.Instant nowUtc = org.joda.time.Instant.now();
DateTimeZone asiaSingapore = DateTimeZone.forID(timeZone);
DateTime nowAsiaSingapore = nowUtc.toDateTime(asiaSingapore);
System.out.println(String.format("Joda-time: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(),
nowAsiaSingapore.toString(PATTERN)));
Assert.assertEquals(nowUtc.toInstant().getMillis(), nowAsiaSingapore.toInstant().getMillis());
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone());
}
}

View File

@ -0,0 +1,87 @@
package com.baeldung.list;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.*;
public class AddElementsUnitTest {
List<Flower> flowers;
@Before
public void init() {
this.flowers = new ArrayList<>(Arrays.asList(
new Flower("Poppy", 12),
new Flower("Anemone", 8),
new Flower("Catmint", 12)));
}
@Test
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() {
List<Flower> anotherList = new ArrayList<>();
anotherList.addAll(flowers);
assertEquals(anotherList.size(), flowers.size());
Assert.assertTrue(anotherList.containsAll(flowers));
}
@Test
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() {
List<Flower> anotherList = new ArrayList<>();
anotherList.addAll(flowers);
Flower flower = anotherList.get(0);
flower.setPetals(flowers.get(0).getPetals() * 3);
assertEquals(anotherList.size(), flowers.size());
Assert.assertTrue(anotherList.containsAll(flowers));
}
@Test
public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() {
List<Flower> target = new ArrayList<>();
Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0));
assertEquals(target.size(), 4);
}
@Test
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() {
List<Flower> flowerVase = new ArrayList<>();
flowers.stream()
.skip(1)
.forEachOrdered(flowerVase::add);
assertEquals(flowerVase.size() + 1, flowers.size());
assertFalse(flowerVase.containsAll(flowers));
}
@Test
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() {
List<Flower> flowerVase = new ArrayList<>();
flowers.stream()
.filter(f -> f.getPetals() > 10)
.forEachOrdered(flowerVase::add);
assertEquals(flowerVase.size() + 1, flowers.size());
assertFalse(flowerVase.containsAll(flowers));
}
@Test
public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() {
List<Flower> target = new ArrayList<>();
Optional.ofNullable(flowers)
.ifPresent(target::addAll);
assertNotNull(target);
assertEquals(target.size(), 3);
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.*;
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest {
private final NullSafeCollectionStreamsUsingCommonsEmptyIfNull instance =
new NullSafeCollectionStreamsUsingCommonsEmptyIfNull();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@ -0,0 +1,53 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Kwaje Anthony <kwajeanthony@gmail.com>
*/
public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance =
new NullSafeCollectionStreamsUsingJava8OptionalContainer();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Kwaje Anthony <kwajeanthony@gmail.com>
*/
public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest {
private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance =
new NullSafeCollectionStreamsUsingNullDereferenceCheck();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@ -1,6 +1,7 @@
package com.baeldung.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.Clock;
import java.time.Instant;
@ -9,6 +10,8 @@ import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.junit.Test;
public class CurrentDateTimeUnitTest {
@ -39,5 +42,4 @@ public class CurrentDateTimeUnitTest {
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
}
}

View File

@ -19,11 +19,23 @@
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -50,6 +62,8 @@
<properties>
<!-- testing -->
<assertj.version>3.10.0</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<awaitility.version>1.7.0</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>

View File

@ -0,0 +1,27 @@
package com.baeldung.java9.language.stream;
import static java.util.stream.Collectors.filtering;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class StreamsGroupingCollectionFilter {
static public Map<Integer, List<Integer>> findEvenNumbersAfterGroupingByQuantityOfDigits(Collection<Integer> baseCollection) {
Function<Integer, Integer> getQuantityOfDigits = item -> (int) Math.log10(item) + 1;
return baseCollection.stream()
.collect(groupingBy(getQuantityOfDigits, filtering(item -> item % 2 == 0, toList())));
}
static public Map<Integer, List<Integer>> findEvenNumbersBeforeGroupingByQuantityOfDigits(Collection<Integer> baseCollection) {
return baseCollection.stream()
.filter(item -> item % 2 == 0)
.collect(groupingBy(item -> (int) Math.log10(item) + 1, toList()));
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.java9.maps.initialize;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
public class MapsInitializer {
@SuppressWarnings("unused")
public void createMapWithMapOf() {
Map<String, String> emptyMap = Map.of();
Map<String, String> singletonMap = Map.of("key1", "value");
Map<String, String> map = Map.of("key1","value1", "key2", "value2");
}
public void createMapWithMapEntries() {
Map<String, String> map = Map.ofEntries(
new AbstractMap.SimpleEntry<String, String>("name", "John"),
new AbstractMap.SimpleEntry<String, String>("city", "budapest"),
new AbstractMap.SimpleEntry<String, String>("zip", "000000"),
new AbstractMap.SimpleEntry<String, String>("home", "1231231231")
);
}
@SuppressWarnings("unused")
public void createMutableMaps() {
Map<String, String> map = new HashMap<String, String> (Map.of("key1","value1", "key2", "value2"));
Map<String, String> map2 = new HashMap<String, String> ( Map.ofEntries(
new AbstractMap.SimpleEntry<String, String>("name", "John"),
new AbstractMap.SimpleEntry<String, String>("city", "budapest")));
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.java9.language.stream;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
public class CollectionFilterUnitTest {
private static final Collection<Integer> BASE_INTEGER_COLLECTION = Arrays.asList(9, 12, 55, 56, 101, 115, 8002, 223, 2668, 19, 8);
private static final Map<Integer, List<Integer>> EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP = createExpectedFilterAfterGroupingMap();
private static Map<Integer, List<Integer>> createExpectedFilterAfterGroupingMap() {
Map<Integer, List<Integer>> map = new HashMap<>();
map.put(1, Arrays.asList(8));
map.put(2, Arrays.asList(12, 56));
map.put(3, Collections.emptyList());
map.put(4, Arrays.asList(8002, 2668));
return map;
}
private static final Map<Integer, List<Integer>> EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP = createExpectedFilterBeforeGroupingMap();
private static Map<Integer, List<Integer>> createExpectedFilterBeforeGroupingMap() {
Map<Integer, List<Integer>> map = new HashMap<>();
map.put(1, Arrays.asList(8));
map.put(2, Arrays.asList(12, 56));
map.put(4, Arrays.asList(8002, 2668));
return map;
}
@Test
public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() {
Map<Integer, List<Integer>> filteredAfterGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersAfterGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION);
Map<Integer, List<Integer>> filteredBeforeGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersBeforeGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION);
assertThat(filteredAfterGroupingMap).containsAllEntriesOf(EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP);
assertThat(filteredBeforeGroupingMap).doesNotContainKey(3)
.containsAllEntriesOf(EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP);
}
}

View File

@ -30,3 +30,9 @@
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
- [How to Store Duplicate Keys in a Map in Java?](http://www.baeldung.com/java-map-duplicate-keys)
- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size)
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
- [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering)
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)

View File

@ -36,19 +36,32 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse.collections.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<junit.platform.version>1.2.0</junit.platform.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.6.1</assertj.version>
<eclipse.collections.version>9.2.0</eclipse.collections.version>
</properties>
</project>

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,42 @@
package com.baeldung.convertlisttomap;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.MapUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ConvertListToMapService {
public Map<Integer, Animal> convertListBeforeJava8(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<>();
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> convertListWithApacheCommons(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<>();
MapUtils.populateMap(map, list, Animal::getId);
return map;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.java.filtering;
import java.util.Collection;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
public class CollectionUtilsCollectionFilter {
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> apacheEventNumberPredicate = item -> item % 2 == 0;
CollectionUtils.filter(baseCollection, apacheEventNumberPredicate);
return baseCollection;
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.java.filtering;
import java.util.Collection;
import org.eclipse.collections.api.block.predicate.Predicate;
import org.eclipse.collections.impl.factory.Lists;
import org.eclipse.collections.impl.utility.Iterate;
public class EclipseCollectionsCollectionFilter {
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> eclipsePredicate = item -> item % 2 == 0;
Collection<Integer> filteredList = Lists.mutable.ofAll(baseCollection)
.select(eclipsePredicate);
return filteredList;
}
static public Collection<Integer> findEvenNumbersUsingIterate(Collection<Integer> baseCollection) {
Predicate<Integer> eclipsePredicate = new Predicate<Integer>() {
private static final long serialVersionUID = 1L;
@Override
public boolean accept(Integer arg0) {
return arg0 % 2 == 0;
}
};
Collection<Integer> filteredList = Iterate.select(baseCollection, eclipsePredicate);
return filteredList;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.java.filtering;
import java.util.Collection;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
public class GuavaCollectionFilter {
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> guavaPredicate = item -> item % 2 == 0;
Collection<Integer> filteredCollection = Collections2.filter(baseCollection, guavaPredicate);
return filteredCollection;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.java.filtering;
import java.util.Collection;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class StreamsCollectionFilter {
public static <T> Collection<T> filterCollectionHelperMethod(Collection<T> baseCollection, Predicate<T> predicate) {
return baseCollection.stream()
.filter(predicate)
.collect(Collectors.toList());
}
static public Collection<Integer> findEvenNumbersUsingHelperMethod(Collection<Integer> baseCollection) {
return filterCollectionHelperMethod(baseCollection, item -> item % 2 == 0);
}
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> streamsPredicate = item -> item % 2 == 0;
return baseCollection.stream()
.filter(streamsPredicate)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.java.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,80 @@
package com.baeldung.java.map.initialize;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MapInitializer {
public static Map<String, String> articleMapOne;
static {
articleMapOne = new HashMap<>();
articleMapOne.put("ar01", "Intro to Map");
articleMapOne.put("ar02", "Some article");
}
public static Map<String, String> createSingletonMap() {
Map<String, String> passwordMap = Collections.singletonMap("username1", "password1");
return passwordMap;
}
public Map<String, String> createEmptyMap() {
Map<String, String> emptyMap = Collections.emptyMap();
return emptyMap;
}
public Map<String, String> createUsingDoubleBrace() {
Map<String, String> doubleBraceMap = new HashMap<String, String>() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
put("key1", "value1");
put("key2", "value2");
}
};
return doubleBraceMap;
}
public Map<String, String> createMapUsingStreamStringArray() {
Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
.collect(Collectors.toMap(data -> data[0], data -> data[1]));
return map;
}
public Map<String, Integer> createMapUsingStreamObjectArray() {
Map<String, Integer> map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, })
.collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1]));
return map;
}
public Map<String, Integer> createMapUsingStreamSimpleEntry() {
Map<String, Integer> map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return map;
}
public Map<String, Integer> createMapUsingStreamSimpleImmutableEntry() {
Map<String, Integer> map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return map;
}
public Map<String, String> createImmutableMapWithStreams() {
Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
.collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections::<String, String> unmodifiableMap));
return map;
}
}

View File

@ -0,0 +1,111 @@
package com.baeldung.list.removeall;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class RemoveAll {
static void removeWithWhileLoopPrimitiveElement(List<Integer> list, int element) {
while (list.contains(element)) {
list.remove(element);
}
}
static void removeWithWhileLoopNonPrimitiveElement(List<Integer> list, Integer element) {
while (list.contains(element)) {
list.remove(element);
}
}
static void removeWithWhileLoopStoringFirstOccurrenceIndex(List<Integer> list, Integer element) {
int index;
while ((index = list.indexOf(element)) >= 0) {
list.remove(index);
}
}
static void removeWithCallingRemoveUntilModifies(List<Integer> list, Integer element) {
while (list.remove(element))
;
}
static void removeWithStandardForLoopUsingIndex(List<Integer> list, int element) {
for (int i = 0; i < list.size(); i++) {
if (Objects.equals(element, list.get(i))) {
list.remove(i);
}
}
}
static void removeWithForLoopDecrementOnRemove(List<Integer> list, int element) {
for (int i = 0; i < list.size(); i++) {
if (Objects.equals(element, list.get(i))) {
list.remove(i);
i--;
}
}
}
static void removeWithForLoopIncrementIfRemains(List<Integer> list, int element) {
for (int i = 0; i < list.size();) {
if (Objects.equals(element, list.get(i))) {
list.remove(i);
} else {
i++;
}
}
}
static void removeWithForEachLoop(List<Integer> list, int element) {
for (Integer number : list) {
if (Objects.equals(number, element)) {
list.remove(number);
}
}
}
static void removeWithIterator(List<Integer> list, int element) {
for (Iterator<Integer> i = list.iterator(); i.hasNext();) {
Integer number = i.next();
if (Objects.equals(number, element)) {
i.remove();
}
}
}
static List<Integer> removeWithCollectingAndReturningRemainingElements(List<Integer> list, int element) {
List<Integer> remainingElements = new ArrayList<>();
for (Integer number : list) {
if (!Objects.equals(number, element)) {
remainingElements.add(number);
}
}
return remainingElements;
}
static void removeWithCollectingRemainingElementsAndAddingToOriginalList(List<Integer> list, int element) {
List<Integer> remainingElements = new ArrayList<>();
for (Integer number : list) {
if (!Objects.equals(number, element)) {
remainingElements.add(number);
}
}
list.clear();
list.addAll(remainingElements);
}
static List<Integer> removeWithStreamFilter(List<Integer> list, Integer element) {
return list.stream()
.filter(e -> !Objects.equals(e, element))
.collect(Collectors.toList());
}
static void removeWithRemoveIf(List<Integer> list, Integer element) {
list.removeIf(n -> Objects.equals(n, element));
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull {
/**
* This method shows how to make a null safe stream from a collection through the use of
* emptyIfNull() method from Apache Commons CollectionUtils library
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return emptyIfNull(collection).stream();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingJava8OptionalContainer {
/**
* This method shows how to make a null safe stream from a collection through the use of
* Java SE 8s Optional Container
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return Optional.ofNullable(collection)
.map(Collection::stream)
.orElseGet(Stream::empty);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingNullDereferenceCheck {
/**
* This method shows how to make a null safe stream from a collection through the use of a check
* to prevent null dereferences
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return collection == null ? Stream.empty() : collection.stream();
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.thread_safe_lifo;
import java.util.ArrayDeque;
/**
* Deque Based Stack implementation.
*/
public class DequeBasedSynchronizedStack<T> {
// Internal Deque which gets decorated for synchronization.
private ArrayDeque<T> dequeStore = new ArrayDeque<>();
public DequeBasedSynchronizedStack(int initialCapacity) {
this.dequeStore = new ArrayDeque<>(initialCapacity);
}
public DequeBasedSynchronizedStack() {
}
public synchronized T pop() {
return this.dequeStore.pop();
}
public synchronized void push(T element) {
this.dequeStore.push(element);
}
public synchronized T peek() {
return this.dequeStore.peek();
}
public synchronized int size() {
return this.dequeStore.size();
}
}

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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,68 @@
package com.baeldung.convertlisttomap;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
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_whenConvertWithApacheCommons_thenReturnMapWithTheSameElements() {
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons(list);
assertThat(map.values(), containsInAnyOrder(list.toArray()));
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.convertlisttomap;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
public class ConvertListWithDiplicatedIdToMapServiceUnitTest {
List<Animal> duplicatedIdList;
private ConvertListToMapService convertListService = new ConvertListToMapService();
@Before
public void init() {
this.duplicatedIdList = new ArrayList<>();
Animal cat = new Animal(1, "Cat");
duplicatedIdList.add(cat);
Animal dog = new Animal(2, "Dog");
duplicatedIdList.add(dog);
Animal pig = new Animal(3, "Pig");
duplicatedIdList.add(pig);
Animal cow = new Animal(4, "Cow");
duplicatedIdList.add(cow);
Animal goat = new Animal(4, "Goat");
duplicatedIdList.add(goat);
}
@Test
public void givenADupIdList_whenConvertBeforeJava8_thenReturnMapWithRewrittenElement() {
Map<Integer, Animal> map = convertListService.convertListBeforeJava8(duplicatedIdList);
assertThat(map.values(), hasSize(4));
assertThat(map.values(), hasItem(duplicatedIdList.get(4)));
}
@Test
public void givenADupIdList_whenConvertWithApacheCommons_thenReturnMapWithRewrittenElement() {
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons(duplicatedIdList);
assertThat(map.values(), hasSize(4));
assertThat(map.values(), hasItem(duplicatedIdList.get(4)));
}
@Test(expected = IllegalStateException.class)
public void givenADupIdList_whenConvertAfterJava8_thenException() {
convertListService.convertListAfterJava8(duplicatedIdList);
}
@Test(expected = IllegalArgumentException.class)
public void givenADupIdList_whenConvertWithGuava_thenException() {
convertListService.convertListWithGuava(duplicatedIdList);
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.java.filtering;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
public class CollectionFiltersUnitTest {
private static final Collection<Integer> BASE_INTEGER_COLLECTION = Arrays.asList(9, 14, 2, 7, 1, 5, 8);
private static final Collection<Integer> EXPECTED_EVEN_FILTERED_COLLECTION = Arrays.asList(14, 2, 8);
@Test
public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() {
final Collection<String> baseStrings = Arrays.asList("java", "baeldung", "type", "example", "other");
Collection<String> filtered = StreamsCollectionFilter.filterCollectionHelperMethod(baseStrings, item -> item.length() == 4);
assertThat(filtered).containsExactlyInAnyOrder("java", "type");
}
@Test
public void givenAnIntegerCollection_whenFilteringEvenValues_thenObtainTheFilteredCollectionForAllCases() {
Collection<Integer> filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
Collection<Integer> filteredWithCollectionUtils = CollectionUtilsCollectionFilter.findEvenNumbers(new ArrayList<>(BASE_INTEGER_COLLECTION));
Collection<Integer> filteredWithEclipseCollections = EclipseCollectionsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
Collection<Integer> filteredWithEclipseCollectionsUsingIterate = EclipseCollectionsCollectionFilter.findEvenNumbersUsingIterate(BASE_INTEGER_COLLECTION);
Collection<Integer> filteredWithGuava = GuavaCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithCollectionUtils)
.hasSameElementsAs(filteredWithEclipseCollections)
.hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate)
.hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate)
.hasSameElementsAs(filteredWithGuava)
.hasSameElementsAs(EXPECTED_EVEN_FILTERED_COLLECTION);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.java.map.initialize;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.Test;
public class MapInitializerUnitTest {
@Test
public void givenStaticMap_whenUpdated_thenCorrect() {
MapInitializer.articleMapOne.put("NewArticle1", "Convert array to List");
assertEquals(MapInitializer.articleMapOne.get("NewArticle1"), "Convert array to List");
}
@Test(expected=UnsupportedOperationException.class)
public void givenSingleTonMap_whenEntriesAdded_throwsException() {
Map<String, String> map = MapInitializer.createSingletonMap();
map.put("username2", "password2");
}
}

View File

@ -50,22 +50,9 @@ public class HashSetInitalizingUnitTest {
@Test
public void whenUsingJava8_usingCollectOnStream_thenCorrectSize() {
Set<String> set = Stream.of("a", "b", "c").collect(Collectors.toSet());
Set<String> set = Stream.of("a", "b", "c").collect(Collectors.toCollection(HashSet::new));
assertEquals(3, set.size());
}
@Test
public void whenUsingJava8_fromStringArray_thenCorrectSize() {
String[] stringArray = {"a","b","c"};
Set<String> set = Arrays.stream(stringArray).collect(Collectors.toCollection(HashSet::new));
assertEquals(3, set.size());
}
// Requires Java9 - uncomment if you are using Java 9 or higher
/*@Test
public void whenUsingJava9_usingCollectOnStream_thenCorrectSize() {
Set set = Set.of("a", "b", "c");
assertEquals(3, set.size());
}*/
@Test
public void whenUsingGoogleGuava_createMutableSet_thenCorrectSize() {
@ -78,4 +65,6 @@ public class HashSetInitalizingUnitTest {
Set<String> set = ImmutableSet.of("a", "b", "c");
assertEquals(3, set.size());
}
}

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