Merge branch 'master' of git://github.com/eugenp/tutorials
* 'master' of git://github.com/eugenp/tutorials: (236 commits) Removing unused files. Removing unused file. Moving file parser inside the core-java module. Adding Test cases for reading files. Revert "A simple Real Time streaming example with Spring Webflux." Examples for Reading a file into an arraylist. 1. Using FileReader 2. Using BufferedReader 3. Using Scanner(String and int) 4. Using Files.readAllLines A simple Real Time streaming example with Spring Webflux. BAEL-1843 - JUnit4 -> JUnit5 migration guide (#4816) BAEL-7708 04.08.2016 (#4893) [BAEL-1902] Set timezone of a date (#4659) BAEL-1552 - Jersey MVC Support BAEL-1552 - Jersey MVC Support [BAEL-7819] - Reverted guest folder parent changes im pom.xml - Fixed wrong push [BAEL-7819] - Reverted guest folder parent changes im pom.xml add/fix links - team BAEL-7962 (#4891) [BAEL-7819] - Added standard parent pom and added start class in sprig-jooq module [BAEL-7819] - Added standard parent pom and fixed tests in those modules Collection to Stream without nulls in core-java-collections (#4903) [BAEL-7670] Added logback.xml in missing modules in src/main/resources Fix typo (#4897) Bael 1964 (#4881) ... # Please enter a commit message to explain why this merge is necessary, # especially if it merges an updated upstream into a topic branch. # # Lines starting with '#' will be ignored, and an empty message aborts # the commit.
This commit is contained in:
commit
d377f2c4cf
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
||||
|
|
|
@ -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>
|
|
@ -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
|
||||
|
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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)
|
||||
|
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Guide to Apache Avro](http://www.baeldung.com/java-apache-avro)
|
|
@ -0,0 +1,88 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-avro-tutorial</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<compiler-plugin.version>3.5</compiler-plugin.version>
|
||||
<avro.version>1.8.2</avro.version>
|
||||
<java.version>1.8</java.version>
|
||||
<slf4j.version>1.7.25</slf4j.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.10</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.avro</groupId>
|
||||
<artifactId>avro</artifactId>
|
||||
<version>${avro.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.avro</groupId>
|
||||
<artifactId>avro-compiler</artifactId>
|
||||
<version>${avro.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.avro</groupId>
|
||||
<artifactId>avro-maven-plugin</artifactId>
|
||||
<version>${avro.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.avro</groupId>
|
||||
<artifactId>avro-maven-plugin</artifactId>
|
||||
<version>${avro.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>schemas</id>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>schema</goal>
|
||||
<goal>protocol</goal>
|
||||
<goal>idl-protocol</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sourceDirectory>${project.basedir}/src/main/resources/</sourceDirectory>
|
||||
<outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.avro.util;
|
||||
|
||||
import org.apache.avro.Schema;
|
||||
import org.apache.avro.compiler.specific.SpecificCompiler;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
public class AvroClassGenerator {
|
||||
public void generateAvroClasses() throws IOException {
|
||||
SpecificCompiler compiler = new SpecificCompiler(new Schema.Parser().parse(new File("src/main/resources/avroHttpRequest-schema.avsc")));
|
||||
compiler.compileToDestination(new File("src/main/resources"), new File("src/main/java"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.avro.util;
|
||||
|
||||
|
||||
import org.apache.avro.Schema;
|
||||
import org.apache.avro.SchemaBuilder;
|
||||
|
||||
public class AvroSchemaBuilder {
|
||||
|
||||
public Schema createAvroHttpRequestSchema(){
|
||||
|
||||
Schema clientIdentifier = SchemaBuilder.record("ClientIdentifier").namespace("com.baeldung.avro.model")
|
||||
.fields().requiredString("hostName").requiredString("ipAddress").endRecord();
|
||||
|
||||
Schema avroHttpRequest = SchemaBuilder.record("AvroHttpRequest").namespace("com.baeldung.avro.model").fields()
|
||||
.requiredLong("requestTime")
|
||||
.name("clientIdentifier").type(clientIdentifier).noDefault()
|
||||
.name("employeeNames").type().array().items().stringType().arrayDefault(null)
|
||||
.name("active").type().enumeration("Active").symbols("YES", "NO").noDefault()
|
||||
.endRecord();
|
||||
return avroHttpRequest;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
/**
|
||||
* Autogenerated by Avro
|
||||
*
|
||||
* DO NOT EDIT DIRECTLY
|
||||
*/
|
||||
package com.baeldung.avro.util.model;
|
||||
@SuppressWarnings("all")
|
||||
@org.apache.avro.specific.AvroGenerated
|
||||
public enum Active {
|
||||
YES, NO ;
|
||||
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"enum\",\"name\":\"Active\",\"namespace\":\"com.baeldung.avro.model\",\"symbols\":[\"YES\",\"NO\"]}");
|
||||
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
|
||||
}
|
|
@ -0,0 +1,491 @@
|
|||
/**
|
||||
* Autogenerated by Avro
|
||||
*
|
||||
* DO NOT EDIT DIRECTLY
|
||||
*/
|
||||
package com.baeldung.avro.util.model;
|
||||
|
||||
import org.apache.avro.specific.SpecificData;
|
||||
import org.apache.avro.message.BinaryMessageEncoder;
|
||||
import org.apache.avro.message.BinaryMessageDecoder;
|
||||
import org.apache.avro.message.SchemaStore;
|
||||
|
||||
@SuppressWarnings("all")
|
||||
@org.apache.avro.specific.AvroGenerated
|
||||
public class AvroHttpRequest extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
|
||||
private static final long serialVersionUID = -8649010116827875312L;
|
||||
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"AvroHttpRequest\",\"namespace\":\"com.baeldung.avro.model\",\"fields\":[{\"name\":\"requestTime\",\"type\":\"long\"},{\"name\":\"clientIdentifier\",\"type\":{\"type\":\"record\",\"name\":\"ClientIdentifier\",\"fields\":[{\"name\":\"hostName\",\"type\":\"string\"},{\"name\":\"ipAddress\",\"type\":\"string\"}]}},{\"name\":\"employeeNames\",\"type\":{\"type\":\"array\",\"items\":\"string\"},\"default\":null},{\"name\":\"active\",\"type\":{\"type\":\"enum\",\"name\":\"Active\",\"symbols\":[\"YES\",\"NO\"]}}]}");
|
||||
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
|
||||
|
||||
private static SpecificData MODEL$ = new SpecificData();
|
||||
|
||||
private static final BinaryMessageEncoder<AvroHttpRequest> ENCODER =
|
||||
new BinaryMessageEncoder<AvroHttpRequest>(MODEL$, SCHEMA$);
|
||||
|
||||
private static final BinaryMessageDecoder<AvroHttpRequest> DECODER =
|
||||
new BinaryMessageDecoder<AvroHttpRequest>(MODEL$, SCHEMA$);
|
||||
|
||||
/**
|
||||
* Return the BinaryMessageDecoder instance used by this class.
|
||||
*/
|
||||
public static BinaryMessageDecoder<AvroHttpRequest> getDecoder() {
|
||||
return DECODER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
|
||||
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
|
||||
*/
|
||||
public static BinaryMessageDecoder<AvroHttpRequest> createDecoder(SchemaStore resolver) {
|
||||
return new BinaryMessageDecoder<AvroHttpRequest>(MODEL$, SCHEMA$, resolver);
|
||||
}
|
||||
|
||||
/** Serializes this AvroHttpRequest to a ByteBuffer. */
|
||||
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
|
||||
return ENCODER.encode(this);
|
||||
}
|
||||
|
||||
/** Deserializes a AvroHttpRequest from a ByteBuffer. */
|
||||
public static AvroHttpRequest fromByteBuffer(
|
||||
java.nio.ByteBuffer b) throws java.io.IOException {
|
||||
return DECODER.decode(b);
|
||||
}
|
||||
|
||||
@Deprecated public long requestTime;
|
||||
@Deprecated public ClientIdentifier clientIdentifier;
|
||||
@Deprecated public java.util.List<java.lang.CharSequence> employeeNames;
|
||||
@Deprecated public Active active;
|
||||
|
||||
/**
|
||||
* Default constructor. Note that this does not initialize fields
|
||||
* to their default values from the schema. If that is desired then
|
||||
* one should use <code>newBuilder()</code>.
|
||||
*/
|
||||
public AvroHttpRequest() {}
|
||||
|
||||
/**
|
||||
* All-args constructor.
|
||||
* @param requestTime The new value for requestTime
|
||||
* @param clientIdentifier The new value for clientIdentifier
|
||||
* @param employeeNames The new value for employeeNames
|
||||
* @param active The new value for active
|
||||
*/
|
||||
public AvroHttpRequest(java.lang.Long requestTime, ClientIdentifier clientIdentifier, java.util.List<java.lang.CharSequence> employeeNames, Active active) {
|
||||
this.requestTime = requestTime;
|
||||
this.clientIdentifier = clientIdentifier;
|
||||
this.employeeNames = employeeNames;
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
|
||||
// Used by DatumWriter. Applications should not call.
|
||||
public java.lang.Object get(int field$) {
|
||||
switch (field$) {
|
||||
case 0: return requestTime;
|
||||
case 1: return clientIdentifier;
|
||||
case 2: return employeeNames;
|
||||
case 3: return active;
|
||||
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
|
||||
}
|
||||
}
|
||||
|
||||
// Used by DatumReader. Applications should not call.
|
||||
@SuppressWarnings(value="unchecked")
|
||||
public void put(int field$, java.lang.Object value$) {
|
||||
switch (field$) {
|
||||
case 0: requestTime = (java.lang.Long)value$; break;
|
||||
case 1: clientIdentifier = (ClientIdentifier)value$; break;
|
||||
case 2: employeeNames = (java.util.List<java.lang.CharSequence>)value$; break;
|
||||
case 3: active = (Active)value$; break;
|
||||
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'requestTime' field.
|
||||
* @return The value of the 'requestTime' field.
|
||||
*/
|
||||
public java.lang.Long getRequestTime() {
|
||||
return requestTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'requestTime' field.
|
||||
* @param value the value to set.
|
||||
*/
|
||||
public void setRequestTime(java.lang.Long value) {
|
||||
this.requestTime = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'clientIdentifier' field.
|
||||
* @return The value of the 'clientIdentifier' field.
|
||||
*/
|
||||
public ClientIdentifier getClientIdentifier() {
|
||||
return clientIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'clientIdentifier' field.
|
||||
* @param value the value to set.
|
||||
*/
|
||||
public void setClientIdentifier(ClientIdentifier value) {
|
||||
this.clientIdentifier = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'employeeNames' field.
|
||||
* @return The value of the 'employeeNames' field.
|
||||
*/
|
||||
public java.util.List<java.lang.CharSequence> getEmployeeNames() {
|
||||
return employeeNames;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'employeeNames' field.
|
||||
* @param value the value to set.
|
||||
*/
|
||||
public void setEmployeeNames(java.util.List<java.lang.CharSequence> value) {
|
||||
this.employeeNames = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'active' field.
|
||||
* @return The value of the 'active' field.
|
||||
*/
|
||||
public Active getActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'active' field.
|
||||
* @param value the value to set.
|
||||
*/
|
||||
public void setActive(Active value) {
|
||||
this.active = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new AvroHttpRequest RecordBuilder.
|
||||
* @return A new AvroHttpRequest RecordBuilder
|
||||
*/
|
||||
public static AvroHttpRequest.Builder newBuilder() {
|
||||
return new AvroHttpRequest.Builder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new AvroHttpRequest RecordBuilder by copying an existing Builder.
|
||||
* @param other The existing builder to copy.
|
||||
* @return A new AvroHttpRequest RecordBuilder
|
||||
*/
|
||||
public static AvroHttpRequest.Builder newBuilder(AvroHttpRequest.Builder other) {
|
||||
return new AvroHttpRequest.Builder(other);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new AvroHttpRequest RecordBuilder by copying an existing AvroHttpRequest instance.
|
||||
* @param other The existing instance to copy.
|
||||
* @return A new AvroHttpRequest RecordBuilder
|
||||
*/
|
||||
public static AvroHttpRequest.Builder newBuilder(AvroHttpRequest other) {
|
||||
return new AvroHttpRequest.Builder(other);
|
||||
}
|
||||
|
||||
/**
|
||||
* RecordBuilder for AvroHttpRequest instances.
|
||||
*/
|
||||
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<AvroHttpRequest>
|
||||
implements org.apache.avro.data.RecordBuilder<AvroHttpRequest> {
|
||||
|
||||
private long requestTime;
|
||||
private ClientIdentifier clientIdentifier;
|
||||
private ClientIdentifier.Builder clientIdentifierBuilder;
|
||||
private java.util.List<java.lang.CharSequence> employeeNames;
|
||||
private Active active;
|
||||
|
||||
/** Creates a new Builder */
|
||||
private Builder() {
|
||||
super(SCHEMA$);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Builder by copying an existing Builder.
|
||||
* @param other The existing Builder to copy.
|
||||
*/
|
||||
private Builder(AvroHttpRequest.Builder other) {
|
||||
super(other);
|
||||
if (isValidValue(fields()[0], other.requestTime)) {
|
||||
this.requestTime = data().deepCopy(fields()[0].schema(), other.requestTime);
|
||||
fieldSetFlags()[0] = true;
|
||||
}
|
||||
if (isValidValue(fields()[1], other.clientIdentifier)) {
|
||||
this.clientIdentifier = data().deepCopy(fields()[1].schema(), other.clientIdentifier);
|
||||
fieldSetFlags()[1] = true;
|
||||
}
|
||||
if (other.hasClientIdentifierBuilder()) {
|
||||
this.clientIdentifierBuilder = ClientIdentifier.newBuilder(other.getClientIdentifierBuilder());
|
||||
}
|
||||
if (isValidValue(fields()[2], other.employeeNames)) {
|
||||
this.employeeNames = data().deepCopy(fields()[2].schema(), other.employeeNames);
|
||||
fieldSetFlags()[2] = true;
|
||||
}
|
||||
if (isValidValue(fields()[3], other.active)) {
|
||||
this.active = data().deepCopy(fields()[3].schema(), other.active);
|
||||
fieldSetFlags()[3] = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Builder by copying an existing AvroHttpRequest instance
|
||||
* @param other The existing instance to copy.
|
||||
*/
|
||||
private Builder(AvroHttpRequest other) {
|
||||
super(SCHEMA$);
|
||||
if (isValidValue(fields()[0], other.requestTime)) {
|
||||
this.requestTime = data().deepCopy(fields()[0].schema(), other.requestTime);
|
||||
fieldSetFlags()[0] = true;
|
||||
}
|
||||
if (isValidValue(fields()[1], other.clientIdentifier)) {
|
||||
this.clientIdentifier = data().deepCopy(fields()[1].schema(), other.clientIdentifier);
|
||||
fieldSetFlags()[1] = true;
|
||||
}
|
||||
this.clientIdentifierBuilder = null;
|
||||
if (isValidValue(fields()[2], other.employeeNames)) {
|
||||
this.employeeNames = data().deepCopy(fields()[2].schema(), other.employeeNames);
|
||||
fieldSetFlags()[2] = true;
|
||||
}
|
||||
if (isValidValue(fields()[3], other.active)) {
|
||||
this.active = data().deepCopy(fields()[3].schema(), other.active);
|
||||
fieldSetFlags()[3] = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'requestTime' field.
|
||||
* @return The value.
|
||||
*/
|
||||
public java.lang.Long getRequestTime() {
|
||||
return requestTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'requestTime' field.
|
||||
* @param value The value of 'requestTime'.
|
||||
* @return This builder.
|
||||
*/
|
||||
public AvroHttpRequest.Builder setRequestTime(long value) {
|
||||
validate(fields()[0], value);
|
||||
this.requestTime = value;
|
||||
fieldSetFlags()[0] = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the 'requestTime' field has been set.
|
||||
* @return True if the 'requestTime' field has been set, false otherwise.
|
||||
*/
|
||||
public boolean hasRequestTime() {
|
||||
return fieldSetFlags()[0];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Clears the value of the 'requestTime' field.
|
||||
* @return This builder.
|
||||
*/
|
||||
public AvroHttpRequest.Builder clearRequestTime() {
|
||||
fieldSetFlags()[0] = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'clientIdentifier' field.
|
||||
* @return The value.
|
||||
*/
|
||||
public ClientIdentifier getClientIdentifier() {
|
||||
return clientIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'clientIdentifier' field.
|
||||
* @param value The value of 'clientIdentifier'.
|
||||
* @return This builder.
|
||||
*/
|
||||
public AvroHttpRequest.Builder setClientIdentifier(ClientIdentifier value) {
|
||||
validate(fields()[1], value);
|
||||
this.clientIdentifierBuilder = null;
|
||||
this.clientIdentifier = value;
|
||||
fieldSetFlags()[1] = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the 'clientIdentifier' field has been set.
|
||||
* @return True if the 'clientIdentifier' field has been set, false otherwise.
|
||||
*/
|
||||
public boolean hasClientIdentifier() {
|
||||
return fieldSetFlags()[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Builder instance for the 'clientIdentifier' field and creates one if it doesn't exist yet.
|
||||
* @return This builder.
|
||||
*/
|
||||
public ClientIdentifier.Builder getClientIdentifierBuilder() {
|
||||
if (clientIdentifierBuilder == null) {
|
||||
if (hasClientIdentifier()) {
|
||||
setClientIdentifierBuilder(ClientIdentifier.newBuilder(clientIdentifier));
|
||||
} else {
|
||||
setClientIdentifierBuilder(ClientIdentifier.newBuilder());
|
||||
}
|
||||
}
|
||||
return clientIdentifierBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Builder instance for the 'clientIdentifier' field
|
||||
* @param value The builder instance that must be set.
|
||||
* @return This builder.
|
||||
*/
|
||||
public AvroHttpRequest.Builder setClientIdentifierBuilder(ClientIdentifier.Builder value) {
|
||||
clearClientIdentifier();
|
||||
clientIdentifierBuilder = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the 'clientIdentifier' field has an active Builder instance
|
||||
* @return True if the 'clientIdentifier' field has an active Builder instance
|
||||
*/
|
||||
public boolean hasClientIdentifierBuilder() {
|
||||
return clientIdentifierBuilder != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the value of the 'clientIdentifier' field.
|
||||
* @return This builder.
|
||||
*/
|
||||
public AvroHttpRequest.Builder clearClientIdentifier() {
|
||||
clientIdentifier = null;
|
||||
clientIdentifierBuilder = null;
|
||||
fieldSetFlags()[1] = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'employeeNames' field.
|
||||
* @return The value.
|
||||
*/
|
||||
public java.util.List<java.lang.CharSequence> getEmployeeNames() {
|
||||
return employeeNames;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'employeeNames' field.
|
||||
* @param value The value of 'employeeNames'.
|
||||
* @return This builder.
|
||||
*/
|
||||
public AvroHttpRequest.Builder setEmployeeNames(java.util.List<java.lang.CharSequence> value) {
|
||||
validate(fields()[2], value);
|
||||
this.employeeNames = value;
|
||||
fieldSetFlags()[2] = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the 'employeeNames' field has been set.
|
||||
* @return True if the 'employeeNames' field has been set, false otherwise.
|
||||
*/
|
||||
public boolean hasEmployeeNames() {
|
||||
return fieldSetFlags()[2];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Clears the value of the 'employeeNames' field.
|
||||
* @return This builder.
|
||||
*/
|
||||
public AvroHttpRequest.Builder clearEmployeeNames() {
|
||||
employeeNames = null;
|
||||
fieldSetFlags()[2] = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'active' field.
|
||||
* @return The value.
|
||||
*/
|
||||
public Active getActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'active' field.
|
||||
* @param value The value of 'active'.
|
||||
* @return This builder.
|
||||
*/
|
||||
public AvroHttpRequest.Builder setActive(Active value) {
|
||||
validate(fields()[3], value);
|
||||
this.active = value;
|
||||
fieldSetFlags()[3] = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the 'active' field has been set.
|
||||
* @return True if the 'active' field has been set, false otherwise.
|
||||
*/
|
||||
public boolean hasActive() {
|
||||
return fieldSetFlags()[3];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Clears the value of the 'active' field.
|
||||
* @return This builder.
|
||||
*/
|
||||
public AvroHttpRequest.Builder clearActive() {
|
||||
active = null;
|
||||
fieldSetFlags()[3] = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public AvroHttpRequest build() {
|
||||
try {
|
||||
AvroHttpRequest record = new AvroHttpRequest();
|
||||
record.requestTime = fieldSetFlags()[0] ? this.requestTime : (java.lang.Long) defaultValue(fields()[0]);
|
||||
if (clientIdentifierBuilder != null) {
|
||||
record.clientIdentifier = this.clientIdentifierBuilder.build();
|
||||
} else {
|
||||
record.clientIdentifier = fieldSetFlags()[1] ? this.clientIdentifier : (ClientIdentifier) defaultValue(fields()[1]);
|
||||
}
|
||||
record.employeeNames = fieldSetFlags()[2] ? this.employeeNames : (java.util.List<java.lang.CharSequence>) defaultValue(fields()[2]);
|
||||
record.active = fieldSetFlags()[3] ? this.active : (Active) defaultValue(fields()[3]);
|
||||
return record;
|
||||
} catch (java.lang.Exception e) {
|
||||
throw new org.apache.avro.AvroRuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static final org.apache.avro.io.DatumWriter<AvroHttpRequest>
|
||||
WRITER$ = (org.apache.avro.io.DatumWriter<AvroHttpRequest>)MODEL$.createDatumWriter(SCHEMA$);
|
||||
|
||||
@Override public void writeExternal(java.io.ObjectOutput out)
|
||||
throws java.io.IOException {
|
||||
WRITER$.write(this, SpecificData.getEncoder(out));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static final org.apache.avro.io.DatumReader<AvroHttpRequest>
|
||||
READER$ = (org.apache.avro.io.DatumReader<AvroHttpRequest>)MODEL$.createDatumReader(SCHEMA$);
|
||||
|
||||
@Override public void readExternal(java.io.ObjectInput in)
|
||||
throws java.io.IOException {
|
||||
READER$.read(this, SpecificData.getDecoder(in));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,308 @@
|
|||
/**
|
||||
* Autogenerated by Avro
|
||||
*
|
||||
* DO NOT EDIT DIRECTLY
|
||||
*/
|
||||
package com.baeldung.avro.util.model;
|
||||
|
||||
import org.apache.avro.specific.SpecificData;
|
||||
import org.apache.avro.message.BinaryMessageEncoder;
|
||||
import org.apache.avro.message.BinaryMessageDecoder;
|
||||
import org.apache.avro.message.SchemaStore;
|
||||
|
||||
@SuppressWarnings("all")
|
||||
@org.apache.avro.specific.AvroGenerated
|
||||
public class ClientIdentifier extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
|
||||
private static final long serialVersionUID = 8754570983127295424L;
|
||||
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"ClientIdentifier\",\"namespace\":\"com.baeldung.avro.model\",\"fields\":[{\"name\":\"hostName\",\"type\":\"string\"},{\"name\":\"ipAddress\",\"type\":\"string\"}]}");
|
||||
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
|
||||
|
||||
private static SpecificData MODEL$ = new SpecificData();
|
||||
|
||||
private static final BinaryMessageEncoder<ClientIdentifier> ENCODER =
|
||||
new BinaryMessageEncoder<ClientIdentifier>(MODEL$, SCHEMA$);
|
||||
|
||||
private static final BinaryMessageDecoder<ClientIdentifier> DECODER =
|
||||
new BinaryMessageDecoder<ClientIdentifier>(MODEL$, SCHEMA$);
|
||||
|
||||
/**
|
||||
* Return the BinaryMessageDecoder instance used by this class.
|
||||
*/
|
||||
public static BinaryMessageDecoder<ClientIdentifier> getDecoder() {
|
||||
return DECODER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
|
||||
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
|
||||
*/
|
||||
public static BinaryMessageDecoder<ClientIdentifier> createDecoder(SchemaStore resolver) {
|
||||
return new BinaryMessageDecoder<ClientIdentifier>(MODEL$, SCHEMA$, resolver);
|
||||
}
|
||||
|
||||
/** Serializes this ClientIdentifier to a ByteBuffer. */
|
||||
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
|
||||
return ENCODER.encode(this);
|
||||
}
|
||||
|
||||
/** Deserializes a ClientIdentifier from a ByteBuffer. */
|
||||
public static ClientIdentifier fromByteBuffer(
|
||||
java.nio.ByteBuffer b) throws java.io.IOException {
|
||||
return DECODER.decode(b);
|
||||
}
|
||||
|
||||
@Deprecated public java.lang.CharSequence hostName;
|
||||
@Deprecated public java.lang.CharSequence ipAddress;
|
||||
|
||||
/**
|
||||
* Default constructor. Note that this does not initialize fields
|
||||
* to their default values from the schema. If that is desired then
|
||||
* one should use <code>newBuilder()</code>.
|
||||
*/
|
||||
public ClientIdentifier() {}
|
||||
|
||||
/**
|
||||
* All-args constructor.
|
||||
* @param hostName The new value for hostName
|
||||
* @param ipAddress The new value for ipAddress
|
||||
*/
|
||||
public ClientIdentifier(java.lang.CharSequence hostName, java.lang.CharSequence ipAddress) {
|
||||
this.hostName = hostName;
|
||||
this.ipAddress = ipAddress;
|
||||
}
|
||||
|
||||
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
|
||||
// Used by DatumWriter. Applications should not call.
|
||||
public java.lang.Object get(int field$) {
|
||||
switch (field$) {
|
||||
case 0: return hostName;
|
||||
case 1: return ipAddress;
|
||||
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
|
||||
}
|
||||
}
|
||||
|
||||
// Used by DatumReader. Applications should not call.
|
||||
@SuppressWarnings(value="unchecked")
|
||||
public void put(int field$, java.lang.Object value$) {
|
||||
switch (field$) {
|
||||
case 0: hostName = (java.lang.CharSequence)value$; break;
|
||||
case 1: ipAddress = (java.lang.CharSequence)value$; break;
|
||||
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'hostName' field.
|
||||
* @return The value of the 'hostName' field.
|
||||
*/
|
||||
public java.lang.CharSequence getHostName() {
|
||||
return hostName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'hostName' field.
|
||||
* @param value the value to set.
|
||||
*/
|
||||
public void setHostName(java.lang.CharSequence value) {
|
||||
this.hostName = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'ipAddress' field.
|
||||
* @return The value of the 'ipAddress' field.
|
||||
*/
|
||||
public java.lang.CharSequence getIpAddress() {
|
||||
return ipAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'ipAddress' field.
|
||||
* @param value the value to set.
|
||||
*/
|
||||
public void setIpAddress(java.lang.CharSequence value) {
|
||||
this.ipAddress = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ClientIdentifier RecordBuilder.
|
||||
* @return A new ClientIdentifier RecordBuilder
|
||||
*/
|
||||
public static ClientIdentifier.Builder newBuilder() {
|
||||
return new ClientIdentifier.Builder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ClientIdentifier RecordBuilder by copying an existing Builder.
|
||||
* @param other The existing builder to copy.
|
||||
* @return A new ClientIdentifier RecordBuilder
|
||||
*/
|
||||
public static ClientIdentifier.Builder newBuilder(ClientIdentifier.Builder other) {
|
||||
return new ClientIdentifier.Builder(other);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ClientIdentifier RecordBuilder by copying an existing ClientIdentifier instance.
|
||||
* @param other The existing instance to copy.
|
||||
* @return A new ClientIdentifier RecordBuilder
|
||||
*/
|
||||
public static ClientIdentifier.Builder newBuilder(ClientIdentifier other) {
|
||||
return new ClientIdentifier.Builder(other);
|
||||
}
|
||||
|
||||
/**
|
||||
* RecordBuilder for ClientIdentifier instances.
|
||||
*/
|
||||
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<ClientIdentifier>
|
||||
implements org.apache.avro.data.RecordBuilder<ClientIdentifier> {
|
||||
|
||||
private java.lang.CharSequence hostName;
|
||||
private java.lang.CharSequence ipAddress;
|
||||
|
||||
/** Creates a new Builder */
|
||||
private Builder() {
|
||||
super(SCHEMA$);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Builder by copying an existing Builder.
|
||||
* @param other The existing Builder to copy.
|
||||
*/
|
||||
private Builder(ClientIdentifier.Builder other) {
|
||||
super(other);
|
||||
if (isValidValue(fields()[0], other.hostName)) {
|
||||
this.hostName = data().deepCopy(fields()[0].schema(), other.hostName);
|
||||
fieldSetFlags()[0] = true;
|
||||
}
|
||||
if (isValidValue(fields()[1], other.ipAddress)) {
|
||||
this.ipAddress = data().deepCopy(fields()[1].schema(), other.ipAddress);
|
||||
fieldSetFlags()[1] = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Builder by copying an existing ClientIdentifier instance
|
||||
* @param other The existing instance to copy.
|
||||
*/
|
||||
private Builder(ClientIdentifier other) {
|
||||
super(SCHEMA$);
|
||||
if (isValidValue(fields()[0], other.hostName)) {
|
||||
this.hostName = data().deepCopy(fields()[0].schema(), other.hostName);
|
||||
fieldSetFlags()[0] = true;
|
||||
}
|
||||
if (isValidValue(fields()[1], other.ipAddress)) {
|
||||
this.ipAddress = data().deepCopy(fields()[1].schema(), other.ipAddress);
|
||||
fieldSetFlags()[1] = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'hostName' field.
|
||||
* @return The value.
|
||||
*/
|
||||
public java.lang.CharSequence getHostName() {
|
||||
return hostName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'hostName' field.
|
||||
* @param value The value of 'hostName'.
|
||||
* @return This builder.
|
||||
*/
|
||||
public ClientIdentifier.Builder setHostName(java.lang.CharSequence value) {
|
||||
validate(fields()[0], value);
|
||||
this.hostName = value;
|
||||
fieldSetFlags()[0] = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the 'hostName' field has been set.
|
||||
* @return True if the 'hostName' field has been set, false otherwise.
|
||||
*/
|
||||
public boolean hasHostName() {
|
||||
return fieldSetFlags()[0];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Clears the value of the 'hostName' field.
|
||||
* @return This builder.
|
||||
*/
|
||||
public ClientIdentifier.Builder clearHostName() {
|
||||
hostName = null;
|
||||
fieldSetFlags()[0] = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'ipAddress' field.
|
||||
* @return The value.
|
||||
*/
|
||||
public java.lang.CharSequence getIpAddress() {
|
||||
return ipAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'ipAddress' field.
|
||||
* @param value The value of 'ipAddress'.
|
||||
* @return This builder.
|
||||
*/
|
||||
public ClientIdentifier.Builder setIpAddress(java.lang.CharSequence value) {
|
||||
validate(fields()[1], value);
|
||||
this.ipAddress = value;
|
||||
fieldSetFlags()[1] = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the 'ipAddress' field has been set.
|
||||
* @return True if the 'ipAddress' field has been set, false otherwise.
|
||||
*/
|
||||
public boolean hasIpAddress() {
|
||||
return fieldSetFlags()[1];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Clears the value of the 'ipAddress' field.
|
||||
* @return This builder.
|
||||
*/
|
||||
public ClientIdentifier.Builder clearIpAddress() {
|
||||
ipAddress = null;
|
||||
fieldSetFlags()[1] = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public ClientIdentifier build() {
|
||||
try {
|
||||
ClientIdentifier record = new ClientIdentifier();
|
||||
record.hostName = fieldSetFlags()[0] ? this.hostName : (java.lang.CharSequence) defaultValue(fields()[0]);
|
||||
record.ipAddress = fieldSetFlags()[1] ? this.ipAddress : (java.lang.CharSequence) defaultValue(fields()[1]);
|
||||
return record;
|
||||
} catch (java.lang.Exception e) {
|
||||
throw new org.apache.avro.AvroRuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static final org.apache.avro.io.DatumWriter<ClientIdentifier>
|
||||
WRITER$ = (org.apache.avro.io.DatumWriter<ClientIdentifier>)MODEL$.createDatumWriter(SCHEMA$);
|
||||
|
||||
@Override public void writeExternal(java.io.ObjectOutput out)
|
||||
throws java.io.IOException {
|
||||
WRITER$.write(this, SpecificData.getEncoder(out));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static final org.apache.avro.io.DatumReader<ClientIdentifier>
|
||||
READER$ = (org.apache.avro.io.DatumReader<ClientIdentifier>)MODEL$.createDatumReader(SCHEMA$);
|
||||
|
||||
@Override public void readExternal(java.io.ObjectInput in)
|
||||
throws java.io.IOException {
|
||||
READER$.read(this, SpecificData.getDecoder(in));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.avro.util.serealization;
|
||||
|
||||
import com.baeldung.avro.util.model.AvroHttpRequest;
|
||||
import org.apache.avro.io.DatumReader;
|
||||
import org.apache.avro.io.Decoder;
|
||||
import org.apache.avro.io.DecoderFactory;
|
||||
import org.apache.avro.specific.SpecificDatumReader;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class AvroDeSerealizer {
|
||||
|
||||
public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data){
|
||||
DatumReader<AvroHttpRequest> reader = new SpecificDatumReader<>(AvroHttpRequest.class);
|
||||
Decoder decoder = null;
|
||||
try {
|
||||
decoder = DecoderFactory.get().jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
|
||||
return reader.read(null, decoder);
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data){
|
||||
DatumReader<AvroHttpRequest> employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
|
||||
Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);
|
||||
try {
|
||||
return employeeReader.read(null, decoder);
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.avro.util.serealization;
|
||||
|
||||
import com.baeldung.avro.util.model.AvroHttpRequest;
|
||||
import org.apache.avro.io.*;
|
||||
import org.apache.avro.specific.SpecificDatumWriter;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
public class AvroSerealizer {
|
||||
|
||||
public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request){
|
||||
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
|
||||
byte[] data = new byte[0];
|
||||
ByteArrayOutputStream stream = new ByteArrayOutputStream();
|
||||
Encoder jsonEncoder = null;
|
||||
try {
|
||||
jsonEncoder = EncoderFactory.get().jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
|
||||
writer.write(request, jsonEncoder);
|
||||
jsonEncoder.flush();
|
||||
data = stream.toByteArray();
|
||||
} catch (IOException e) {
|
||||
data =null;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request){
|
||||
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
|
||||
byte[] data = new byte[0];
|
||||
ByteArrayOutputStream stream = new ByteArrayOutputStream();
|
||||
Encoder jsonEncoder = EncoderFactory.get().binaryEncoder(stream,null);
|
||||
try {
|
||||
writer.write(request, jsonEncoder);
|
||||
jsonEncoder.flush();
|
||||
data = stream.toByteArray();
|
||||
} catch (IOException e) {
|
||||
data = null;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
{
|
||||
"type":"record",
|
||||
"name":"AvroHttpRequest",
|
||||
"namespace":"com.baeldung.avro.model",
|
||||
"fields":[
|
||||
{
|
||||
"name":"requestTime",
|
||||
"type":"long"
|
||||
},
|
||||
{
|
||||
"name":"clientIdentifier",
|
||||
"type":{
|
||||
"type":"record",
|
||||
"name":"ClientIdentifier",
|
||||
"fields":[
|
||||
{
|
||||
"name":"hostName",
|
||||
"type":"string"
|
||||
},
|
||||
{
|
||||
"name":"ipAddress",
|
||||
"type":"string"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name":"employeeNames",
|
||||
"type":{
|
||||
"type":"array",
|
||||
"items":"string"
|
||||
},
|
||||
"default":null
|
||||
},
|
||||
{
|
||||
"name":"active",
|
||||
"type":{
|
||||
"type":"enum",
|
||||
"name":"Active",
|
||||
"symbols":[
|
||||
"YES",
|
||||
"NO"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
|
@ -0,0 +1,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>
|
|
@ -0,0 +1,75 @@
|
|||
package com.baeldung.avro.util.serealization;
|
||||
|
||||
import com.baeldung.avro.util.model.Active;
|
||||
import com.baeldung.avro.util.model.AvroHttpRequest;
|
||||
import com.baeldung.avro.util.model.ClientIdentifier;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class AvroSerealizerDeSerealizerTest {
|
||||
|
||||
AvroSerealizer serealizer;
|
||||
AvroDeSerealizer deSerealizer;
|
||||
AvroHttpRequest request;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
serealizer = new AvroSerealizer();
|
||||
deSerealizer = new AvroDeSerealizer();
|
||||
|
||||
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder().
|
||||
setHostName("localhost").setIpAddress("255.255.255.0").build();
|
||||
|
||||
List<CharSequence> employees = new ArrayList();
|
||||
employees.add("James");
|
||||
employees.add("Alice");
|
||||
employees.add("David");
|
||||
employees.add("Han");
|
||||
|
||||
request = AvroHttpRequest.newBuilder().setRequestTime(01l)
|
||||
.setActive(Active.YES).setClientIdentifier(clientIdentifier)
|
||||
.setEmployeeNames(employees).build();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenSerialized_UsingJSONEncoder_ObjectGetsSerialized(){
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
|
||||
assertTrue(Objects.nonNull(data));
|
||||
assertTrue(data.length > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenSerialized_UsingBinaryEncoder_ObjectGetsSerialized(){
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
|
||||
assertTrue(Objects.nonNull(data));
|
||||
assertTrue(data.length > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenDeserialize_UsingJSONDecoder_ActualAndExpectedObjectsAreEqual(){
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
|
||||
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
|
||||
assertEquals(actualRequest,request);
|
||||
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenDeserialize_UsingBinaryecoder_ActualAndExpectedObjectsAreEqual(){
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
|
||||
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
|
||||
assertEquals(actualRequest,request);
|
||||
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
================================
|
||||
- [Building a Microservice with Apache Meecrowave](http://www.baeldung.com/apache-meecrowave)
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
||||
|
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
||||
|
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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)
|
||||
|
|
|
@ -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>
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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>
|
|
@ -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)
|
||||
|
|
|
@ -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>
|
||||
|
@ -128,77 +138,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>
|
||||
|
@ -241,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>
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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 8’s 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);
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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>
|
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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()));
|
||||
}
|
||||
}
|
|
@ -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")));
|
||||
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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)
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.convertlisttomap;
|
||||
|
||||
public class Animal {
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public Animal(int id, String name) {
|
||||
this.id = id;
|
||||
this.setName(name);
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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 8’s 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);
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue