JAVA-1848: new module apache-libraries to group apache-* modules with a
single article
This commit is contained in:
parent
3cb48fd96e
commit
b3df35ba3d
|
@ -0,0 +1,15 @@
|
|||
## Apache Avro
|
||||
|
||||
This module contains articles about Apache Avro
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guide to Apache Avro](https://www.baeldung.com/java-apache-avro)
|
||||
- [Introduction to Apache Beam](https://www.baeldung.com/apache-beam)
|
||||
- [Intro to Apache BVal](https://www.baeldung.com/apache-bval)
|
||||
- [Building a Microservice with Apache Meecrowave](https://www.baeldung.com/apache-meecrowave)
|
||||
- [Intro to Apache OpenNLP](https://www.baeldung.com/apache-open-nlp)
|
||||
- [Introduction to Apache Pulsar](https://www.baeldung.com/apache-pulsar)
|
||||
- [Getting Started with Java and Zookeeper](https://www.baeldung.com/java-zookeeper)
|
||||
- [Introduction to Apache Curator](https://www.baeldung.com/apache-curator)
|
||||
- [A Quick Guide to Apache Geode](https://www.baeldung.com/apache-geode)
|
||||
- [Guide to Solr in Java with Apache Solrj](https://www.baeldung.com/apache-solrj)
|
|
@ -0,0 +1,223 @@
|
|||
<?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>
|
||||
<artifactId>apache-miscellaneous-1</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>apache-libraries</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- avro -->
|
||||
<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>
|
||||
|
||||
<!-- beam -->
|
||||
<dependency>
|
||||
<groupId>org.apache.beam</groupId>
|
||||
<artifactId>beam-sdks-java-core</artifactId>
|
||||
<version>${beam.version}</version>
|
||||
</dependency>
|
||||
<!-- runtime scoped -->
|
||||
<dependency>
|
||||
<groupId>org.apache.beam</groupId>
|
||||
<artifactId>beam-runners-direct-java</artifactId>
|
||||
<version>${beam.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- bval -->
|
||||
<dependency>
|
||||
<groupId>org.apache.bval</groupId>
|
||||
<artifactId>bval-jsr</artifactId>
|
||||
<version>${bval.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>${javax.validation.validation-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.bval</groupId>
|
||||
<artifactId>bval-extras</artifactId>
|
||||
<version>${bval.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- meecrowave -->
|
||||
<dependency>
|
||||
<groupId>org.apache.meecrowave</groupId>
|
||||
<artifactId>meecrowave-core</artifactId>
|
||||
<version>${meecrowave-core.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-jpa -->
|
||||
<dependency>
|
||||
<groupId>org.apache.meecrowave</groupId>
|
||||
<artifactId>meecrowave-jpa</artifactId>
|
||||
<version>${meecrowave-jpa.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>${okhttp.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.meecrowave</groupId>
|
||||
<artifactId>meecrowave-junit</artifactId>
|
||||
<version>${meecrowave-junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- opennlp -->
|
||||
<dependency>
|
||||
<groupId>org.apache.opennlp</groupId>
|
||||
<artifactId>opennlp-tools</artifactId>
|
||||
<version>${opennlp.opennlp-tools.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- pulsar -->
|
||||
<dependency>
|
||||
<groupId>org.apache.pulsar</groupId>
|
||||
<artifactId>pulsar-client</artifactId>
|
||||
<version>${pulsar-client.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- zookeeper -->
|
||||
<dependency>
|
||||
<groupId>org.apache.zookeeper</groupId>
|
||||
<artifactId>zookeeper</artifactId>
|
||||
<version>${zookeeper.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- curator -->
|
||||
<dependency>
|
||||
<groupId>org.apache.curator</groupId>
|
||||
<artifactId>curator-x-async</artifactId>
|
||||
<version>${curator.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.zookeeper</groupId>
|
||||
<artifactId>zookeeper</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.curator</groupId>
|
||||
<artifactId>curator-recipes</artifactId>
|
||||
<version>${curator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.zookeeper</groupId>
|
||||
<artifactId>zookeeper</artifactId>
|
||||
<version>${zookeeper.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- geode -->
|
||||
<dependency>
|
||||
<groupId>org.apache.geode</groupId>
|
||||
<artifactId>geode-core</artifactId>
|
||||
<version>${geode.core}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- solr -->
|
||||
<dependency>
|
||||
<groupId>org.apache.solr</groupId>
|
||||
<artifactId>solr-solrj</artifactId>
|
||||
<version>${solr.solr-solrj.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- common -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<!-- avro -->
|
||||
<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>
|
||||
|
||||
<!-- meecrowave -->
|
||||
<plugin>
|
||||
<groupId>org.apache.meecrowave</groupId>
|
||||
<artifactId>meecrowave-maven-plugin</artifactId>
|
||||
<version>${meecrowave-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<avro.version>1.8.2</avro.version>
|
||||
<slf4j.version>1.7.25</slf4j.version>
|
||||
<beam.version>2.19.0</beam.version>
|
||||
<assertj.version>3.9.0</assertj.version>
|
||||
<bval.version>1.1.2</bval.version>
|
||||
<javax.validation.validation-api.version>1.1.0.Final</javax.validation.validation-api.version>
|
||||
<meecrowave-junit.version>1.2.0</meecrowave-junit.version>
|
||||
<okhttp.version>3.10.0</okhttp.version>
|
||||
<meecrowave-jpa.version>1.2.1</meecrowave-jpa.version>
|
||||
<meecrowave-core.version>1.2.1</meecrowave-core.version>
|
||||
<meecrowave-maven-plugin.version>1.2.1</meecrowave-maven-plugin.version>
|
||||
<opennlp.opennlp-tools.version>1.8.4</opennlp.opennlp-tools.version>
|
||||
<pulsar-client.version>2.1.1-incubating</pulsar-client.version>
|
||||
<zookeeper.version>3.4.11</zookeeper.version>
|
||||
<curator.version>4.0.1</curator.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<geode.core>1.6.0</geode.core>
|
||||
<solr.solr-solrj.version>6.4.0</solr.solr-solrj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,71 @@
|
|||
package com.baeldung.apache.beam.intro;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.beam.sdk.Pipeline;
|
||||
import org.apache.beam.sdk.io.TextIO;
|
||||
import org.apache.beam.sdk.options.PipelineOptions;
|
||||
import org.apache.beam.sdk.options.PipelineOptionsFactory;
|
||||
import org.apache.beam.sdk.transforms.Count;
|
||||
import org.apache.beam.sdk.transforms.Filter;
|
||||
import org.apache.beam.sdk.transforms.FlatMapElements;
|
||||
import org.apache.beam.sdk.transforms.MapElements;
|
||||
import org.apache.beam.sdk.values.KV;
|
||||
import org.apache.beam.sdk.values.PCollection;
|
||||
import org.apache.beam.sdk.values.TypeDescriptors;
|
||||
|
||||
public class WordCount {
|
||||
|
||||
public static boolean wordCount(String inputFilePath, String outputFilePath) {
|
||||
// We use default options
|
||||
PipelineOptions options = PipelineOptionsFactory.create();
|
||||
// to create the pipeline
|
||||
Pipeline p = Pipeline.create(options);
|
||||
// Here is our workflow graph
|
||||
PCollection<KV<String, Long>> wordCount = p
|
||||
.apply("(1) Read all lines", TextIO.read().from(inputFilePath))
|
||||
.apply("(2) Flatmap to a list of words", FlatMapElements.into(TypeDescriptors.strings())
|
||||
.via(line -> Arrays.asList(line.split("\\s"))))
|
||||
.apply("(3) Lowercase all", MapElements.into(TypeDescriptors.strings())
|
||||
.via(word -> word.toLowerCase()))
|
||||
.apply("(4) Trim punctuations", MapElements.into(TypeDescriptors.strings())
|
||||
.via(word -> trim(word)))
|
||||
.apply("(5) Filter stopwords", Filter.by(word -> !isStopWord(word)))
|
||||
.apply("(6) Count words", Count.perElement());
|
||||
// We convert the PCollection to String so that we can write it to file
|
||||
wordCount.apply(MapElements.into(TypeDescriptors.strings())
|
||||
.via(count -> count.getKey() + " --> " + count.getValue()))
|
||||
.apply(TextIO.write().to(outputFilePath));
|
||||
// Finally we must run the pipeline, otherwise it's only a definition
|
||||
p.run().waitUntilFinish();
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isStopWord(String word) {
|
||||
String[] stopwords = {"am", "are", "is", "i", "you", "me",
|
||||
"he", "she", "they", "them", "was",
|
||||
"were", "from", "in", "of", "to", "be",
|
||||
"him", "her", "us", "and", "or"};
|
||||
for (String stopword : stopwords) {
|
||||
if (stopword.compareTo(word) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static String trim(String word) {
|
||||
return word.replace("(","")
|
||||
.replace(")", "")
|
||||
.replace(",", "")
|
||||
.replace(".", "")
|
||||
.replace("\"", "")
|
||||
.replace("'", "")
|
||||
.replace(":", "")
|
||||
.replace(";", "")
|
||||
.replace("-", "")
|
||||
.replace("?", "")
|
||||
.replace("!", "");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.apache.curator.modeled;
|
||||
|
||||
public class HostConfig {
|
||||
private String hostname;
|
||||
private int port;
|
||||
|
||||
public HostConfig() {
|
||||
|
||||
}
|
||||
|
||||
public HostConfig(String hostname, int port) {
|
||||
this.hostname = hostname;
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void setPort(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public String getHostname() {
|
||||
return hostname;
|
||||
}
|
||||
|
||||
public void setHostname(String hostname) {
|
||||
this.hostname = hostname;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
/**
|
||||
* Autogenerated by Avro
|
||||
*
|
||||
* DO NOT EDIT DIRECTLY
|
||||
*/
|
||||
package com.baeldung.avro.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.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 com.baeldung.avro.model.ClientIdentifier clientIdentifier;
|
||||
@Deprecated public java.util.List<java.lang.CharSequence> employeeNames;
|
||||
@Deprecated public com.baeldung.avro.model.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, com.baeldung.avro.model.ClientIdentifier clientIdentifier, java.util.List<java.lang.CharSequence> employeeNames, com.baeldung.avro.model.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 = (com.baeldung.avro.model.ClientIdentifier)value$; break;
|
||||
case 2: employeeNames = (java.util.List<java.lang.CharSequence>)value$; break;
|
||||
case 3: active = (com.baeldung.avro.model.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 com.baeldung.avro.model.ClientIdentifier getClientIdentifier() {
|
||||
return clientIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'clientIdentifier' field.
|
||||
* @param value the value to set.
|
||||
*/
|
||||
public void setClientIdentifier(com.baeldung.avro.model.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 com.baeldung.avro.model.Active getActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'active' field.
|
||||
* @param value the value to set.
|
||||
*/
|
||||
public void setActive(com.baeldung.avro.model.Active value) {
|
||||
this.active = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new AvroHttpRequest RecordBuilder.
|
||||
* @return A new AvroHttpRequest RecordBuilder
|
||||
*/
|
||||
public static com.baeldung.avro.model.AvroHttpRequest.Builder newBuilder() {
|
||||
return new com.baeldung.avro.model.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 com.baeldung.avro.model.AvroHttpRequest.Builder newBuilder(com.baeldung.avro.model.AvroHttpRequest.Builder other) {
|
||||
return new com.baeldung.avro.model.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 com.baeldung.avro.model.AvroHttpRequest.Builder newBuilder(com.baeldung.avro.model.AvroHttpRequest other) {
|
||||
return new com.baeldung.avro.model.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 com.baeldung.avro.model.ClientIdentifier clientIdentifier;
|
||||
private com.baeldung.avro.model.ClientIdentifier.Builder clientIdentifierBuilder;
|
||||
private java.util.List<java.lang.CharSequence> employeeNames;
|
||||
private com.baeldung.avro.model.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(com.baeldung.avro.model.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 = com.baeldung.avro.model.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(com.baeldung.avro.model.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 com.baeldung.avro.model.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 com.baeldung.avro.model.AvroHttpRequest.Builder clearRequestTime() {
|
||||
fieldSetFlags()[0] = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'clientIdentifier' field.
|
||||
* @return The value.
|
||||
*/
|
||||
public com.baeldung.avro.model.ClientIdentifier getClientIdentifier() {
|
||||
return clientIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'clientIdentifier' field.
|
||||
* @param value The value of 'clientIdentifier'.
|
||||
* @return This builder.
|
||||
*/
|
||||
public com.baeldung.avro.model.AvroHttpRequest.Builder setClientIdentifier(com.baeldung.avro.model.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 com.baeldung.avro.model.ClientIdentifier.Builder getClientIdentifierBuilder() {
|
||||
if (clientIdentifierBuilder == null) {
|
||||
if (hasClientIdentifier()) {
|
||||
setClientIdentifierBuilder(com.baeldung.avro.model.ClientIdentifier.newBuilder(clientIdentifier));
|
||||
} else {
|
||||
setClientIdentifierBuilder(com.baeldung.avro.model.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 com.baeldung.avro.model.AvroHttpRequest.Builder setClientIdentifierBuilder(com.baeldung.avro.model.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 com.baeldung.avro.model.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 com.baeldung.avro.model.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 com.baeldung.avro.model.AvroHttpRequest.Builder clearEmployeeNames() {
|
||||
employeeNames = null;
|
||||
fieldSetFlags()[2] = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the 'active' field.
|
||||
* @return The value.
|
||||
*/
|
||||
public com.baeldung.avro.model.Active getActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the 'active' field.
|
||||
* @param value The value of 'active'.
|
||||
* @return This builder.
|
||||
*/
|
||||
public com.baeldung.avro.model.AvroHttpRequest.Builder setActive(com.baeldung.avro.model.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 com.baeldung.avro.model.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 : (com.baeldung.avro.model.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 : (com.baeldung.avro.model.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.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 com.baeldung.avro.model.ClientIdentifier.Builder newBuilder() {
|
||||
return new com.baeldung.avro.model.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 com.baeldung.avro.model.ClientIdentifier.Builder newBuilder(com.baeldung.avro.model.ClientIdentifier.Builder other) {
|
||||
return new com.baeldung.avro.model.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 com.baeldung.avro.model.ClientIdentifier.Builder newBuilder(com.baeldung.avro.model.ClientIdentifier other) {
|
||||
return new com.baeldung.avro.model.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(com.baeldung.avro.model.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(com.baeldung.avro.model.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 com.baeldung.avro.model.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 com.baeldung.avro.model.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 com.baeldung.avro.model.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 com.baeldung.avro.model.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,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,41 @@
|
|||
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 org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class AvroDeSerealizer {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
|
||||
|
||||
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) {
|
||||
logger.error("Deserialization error" + e.getMessage());
|
||||
}
|
||||
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) {
|
||||
logger.error("Deserialization error" + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
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 org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
public class AvroSerealizer {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class);
|
||||
|
||||
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) {
|
||||
logger.error("Serialization error " + e.getMessage());
|
||||
}
|
||||
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) {
|
||||
logger.error("Serialization error " + e.getMessage());
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,120 @@
|
|||
package com.baeldung.bval.model;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
import org.apache.bval.constraints.Email;
|
||||
import org.apache.bval.constraints.NotEmpty;
|
||||
import org.apache.bval.extras.constraints.checkdigit.IBAN;
|
||||
import org.apache.bval.extras.constraints.creditcard.Visa;
|
||||
import org.apache.bval.extras.constraints.file.Directory;
|
||||
import org.apache.bval.extras.constraints.net.InetAddress;
|
||||
|
||||
import com.baeldung.bval.validation.Password;
|
||||
|
||||
public class User {
|
||||
@NotNull
|
||||
@Email
|
||||
private String email;
|
||||
|
||||
@NotEmpty
|
||||
@Password
|
||||
private String password;
|
||||
|
||||
@Size(min = 1, max = 20)
|
||||
private String name;
|
||||
|
||||
@Min(18)
|
||||
private int age;
|
||||
|
||||
@Visa
|
||||
private String cardNumber = "";
|
||||
|
||||
@IBAN
|
||||
private String iban = "";
|
||||
|
||||
@InetAddress
|
||||
private String website = "";
|
||||
|
||||
@Directory
|
||||
private File mainDirectory=new File(".");
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String email, String password, String name, int age) {
|
||||
super();
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getCardNumber() {
|
||||
return cardNumber;
|
||||
}
|
||||
|
||||
public void setCardNumber(String cardNumber) {
|
||||
this.cardNumber = cardNumber;
|
||||
}
|
||||
|
||||
public String getIban() {
|
||||
return iban;
|
||||
}
|
||||
|
||||
public void setIban(String iban) {
|
||||
this.iban = iban;
|
||||
}
|
||||
|
||||
public String getWebsite() {
|
||||
return website;
|
||||
}
|
||||
|
||||
public void setWebsite(String website) {
|
||||
this.website = website;
|
||||
}
|
||||
|
||||
public File getMainDirectory() {
|
||||
return mainDirectory;
|
||||
}
|
||||
|
||||
public void setMainDirectory(File mainDirectory) {
|
||||
this.mainDirectory = mainDirectory;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.bval.validation;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
|
||||
import static java.lang.annotation.ElementType.*;
|
||||
|
||||
@Constraint(validatedBy = { PasswordValidator.class })
|
||||
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Password {
|
||||
String message() default "Invalid password";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
|
||||
int length() default 6;
|
||||
|
||||
int nonAlpha() default 1;
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.bval.validation;
|
||||
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
|
||||
public class PasswordValidator implements ConstraintValidator<Password, String> {
|
||||
|
||||
private int length;
|
||||
private int nonAlpha;
|
||||
|
||||
@Override
|
||||
public void initialize(Password password) {
|
||||
this.length = password.length();
|
||||
this.nonAlpha = password.nonAlpha();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(String value, ConstraintValidatorContext context) {
|
||||
if (value.length() < length) {
|
||||
return false;
|
||||
}
|
||||
int nonAlphaNr = 0;
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
if (!Character.isLetterOrDigit(value.charAt(i))) {
|
||||
nonAlphaNr++;
|
||||
}
|
||||
}
|
||||
if (nonAlphaNr < nonAlpha) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package com.baeldung.geode;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
public class Customer implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = -7482516011038799900L;
|
||||
|
||||
private CustomerKey key;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Integer age;
|
||||
|
||||
public Customer() {
|
||||
}
|
||||
|
||||
public Customer(String firstName, String lastName, int age) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public Customer(CustomerKey key, String firstName, String lastName, int age) {
|
||||
this(firstName, lastName, age);
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
// setters and getters
|
||||
|
||||
public static long getSerialVersionUID() {
|
||||
return serialVersionUID;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Customer customer = (Customer) o;
|
||||
return Objects.equals(firstName, customer.firstName) && Objects.equals(lastName, customer.lastName) && Objects.equals(age, customer.age);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(firstName, lastName, age);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.geode;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class CustomerKey implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = -3529253035303792458L;
|
||||
private long id;
|
||||
private String country;
|
||||
|
||||
public CustomerKey(long id) {
|
||||
this.id = id;
|
||||
this.country = "USA";
|
||||
}
|
||||
|
||||
public CustomerKey(long id, String country) {
|
||||
this.id = id;
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
CustomerKey that = (CustomerKey) o;
|
||||
|
||||
if (id != that.id)
|
||||
return false;
|
||||
return country != null ? country.equals(that.country) : that.country == null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = (int) (id ^ (id >>> 32));
|
||||
result = 31 * result + (country != null ? country.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.geode.functions;
|
||||
|
||||
import com.baeldung.geode.Customer;
|
||||
import com.baeldung.geode.CustomerKey;
|
||||
import org.apache.geode.cache.Region;
|
||||
import org.apache.geode.cache.execute.Function;
|
||||
import org.apache.geode.cache.execute.FunctionContext;
|
||||
import org.apache.geode.cache.execute.RegionFunctionContext;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class UpperCaseNames implements Function<Boolean> {
|
||||
private static final long serialVersionUID = -8946294032165677602L;
|
||||
|
||||
@Override
|
||||
public void execute(FunctionContext<Boolean> context) {
|
||||
RegionFunctionContext regionContext = (RegionFunctionContext) context;
|
||||
Region<CustomerKey, Customer> region = regionContext.getDataSet();
|
||||
|
||||
for (Map.Entry<CustomerKey, Customer> entry : region.entrySet()) {
|
||||
Customer customer = entry.getValue();
|
||||
customer.setFirstName(customer.getFirstName()
|
||||
.toUpperCase());
|
||||
}
|
||||
|
||||
context.getResultSender()
|
||||
.lastResult(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return getClass().getName();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.meecrowave;
|
||||
|
||||
public class Article {
|
||||
private String name;
|
||||
private String author;
|
||||
|
||||
public Article() {
|
||||
}
|
||||
|
||||
public Article(String name, String author) {
|
||||
this.author = author;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.meecrowave;
|
||||
|
||||
import javax.enterprise.context.RequestScoped;
|
||||
import javax.inject.Inject;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
@RequestScoped
|
||||
@Path("article")
|
||||
public class ArticleEndpoints {
|
||||
|
||||
@Inject
|
||||
ArticleService articleService;
|
||||
|
||||
@GET
|
||||
public Response getArticle() {
|
||||
return Response.ok()
|
||||
.entity(new Article("name", "author"))
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
@POST
|
||||
public Response createArticle(Article article) {
|
||||
return Response.status(Status.CREATED)
|
||||
.entity(articleService.createArticle(article))
|
||||
.build();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.meecrowave;
|
||||
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
|
||||
@ApplicationScoped
|
||||
public class ArticleService {
|
||||
public Article createArticle(Article article) {
|
||||
return article;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.meecrowave;
|
||||
|
||||
import org.apache.meecrowave.Meecrowave;
|
||||
|
||||
public class Server {
|
||||
public static void main(String[] args) {
|
||||
final Meecrowave.Builder builder = new Meecrowave.Builder();
|
||||
builder.setScanningPackageIncludes("com.baeldung.meecrowave");
|
||||
builder.setJaxrsMapping("/api/*");
|
||||
builder.setJsonpPrettify(true);
|
||||
|
||||
try (Meecrowave meecrowave = new Meecrowave(builder)) {
|
||||
meecrowave.bake().await();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.pulsar;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.pulsar.client.api.Consumer;
|
||||
import org.apache.pulsar.client.api.Message;
|
||||
import org.apache.pulsar.client.api.PulsarClient;
|
||||
import org.apache.pulsar.client.api.SubscriptionType;
|
||||
|
||||
public class ConsumerUnitTest {
|
||||
|
||||
private static final String SERVICE_URL = "pulsar://localhost:6650";
|
||||
private static final String TOPIC_NAME = "test-topic";
|
||||
private static final String SUBSCRIPTION_NAME = "test-subscription";
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
// Create a Pulsar client instance. A single instance can be shared across many
|
||||
// producers and consumer within the same application
|
||||
PulsarClient client = PulsarClient.builder()
|
||||
.serviceUrl(SERVICE_URL)
|
||||
.build();
|
||||
|
||||
//Configure consumer specific settings.
|
||||
Consumer<byte[]> consumer = client.newConsumer()
|
||||
.topic(TOPIC_NAME)
|
||||
// Allow multiple consumers to attach to the same subscription
|
||||
// and get messages dispatched as a queue
|
||||
.subscriptionType(SubscriptionType.Shared)
|
||||
.subscriptionName(SUBSCRIPTION_NAME)
|
||||
.subscribe();
|
||||
|
||||
|
||||
// Once the consumer is created, it can be used for the entire application lifecycle
|
||||
System.out.println("Created consumer for the topic "+ TOPIC_NAME);
|
||||
|
||||
do {
|
||||
// Wait until a message is available
|
||||
Message<byte[]> msg = consumer.receive();
|
||||
|
||||
// Extract the message as a printable string and then log
|
||||
String content = new String(msg.getData());
|
||||
System.out.println("Received message '"+content+"' with ID "+msg.getMessageId());
|
||||
|
||||
// Acknowledge processing of the message so that it can be deleted
|
||||
consumer.acknowledge(msg);
|
||||
} while (true);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.pulsar;
|
||||
|
||||
import org.apache.pulsar.client.api.CompressionType;
|
||||
import org.apache.pulsar.client.api.Message;
|
||||
import org.apache.pulsar.client.api.MessageBuilder;
|
||||
import org.apache.pulsar.client.api.MessageId;
|
||||
import org.apache.pulsar.client.api.Producer;
|
||||
import org.apache.pulsar.client.api.PulsarClient;
|
||||
import org.apache.pulsar.client.api.PulsarClientException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class ProducerUnitTest {
|
||||
|
||||
private static final String SERVICE_URL = "pulsar://localhost:6650";
|
||||
private static final String TOPIC_NAME = "test-topic";
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
// Create a Pulsar client instance. A single instance can be shared across many
|
||||
// producers and consumer within the same application
|
||||
PulsarClient client = PulsarClient.builder()
|
||||
.serviceUrl(SERVICE_URL)
|
||||
.build();
|
||||
|
||||
// Configure producer specific settings
|
||||
Producer<byte[]> producer = client.newProducer()
|
||||
// Set the topic
|
||||
.topic(TOPIC_NAME)
|
||||
// Enable compression
|
||||
.compressionType(CompressionType.LZ4)
|
||||
.create();
|
||||
|
||||
// Once the producer is created, it can be used for the entire application life-cycle
|
||||
System.out.println("Created producer for the topic "+TOPIC_NAME);
|
||||
|
||||
// Send 5 test messages
|
||||
IntStream.range(1, 5).forEach(i -> {
|
||||
String content = String.format("hi-pulsar-%d", i);
|
||||
|
||||
// Build a message object
|
||||
Message<byte[]> msg = MessageBuilder.create()
|
||||
.setContent(content.getBytes())
|
||||
.build();
|
||||
|
||||
// Send each message and log message content and ID when successfully received
|
||||
try {
|
||||
MessageId msgId = producer.send(msg);
|
||||
|
||||
System.out.println("Published message '"+content+"' with the ID "+msgId);
|
||||
} catch (PulsarClientException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
});
|
||||
|
||||
client.close();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package com.baeldung.pulsar.subscriptions;
|
||||
|
||||
import org.apache.pulsar.client.api.ConsumerBuilder;
|
||||
import org.apache.pulsar.client.api.Message;
|
||||
import org.apache.pulsar.client.api.MessageBuilder;
|
||||
import org.apache.pulsar.client.api.Producer;
|
||||
import org.apache.pulsar.client.api.PulsarClient;
|
||||
import org.apache.pulsar.client.api.PulsarClientException;
|
||||
import org.apache.pulsar.client.api.SubscriptionType;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class ExclusiveSubscriptionUnitTest {
|
||||
private static final String SERVICE_URL = "pulsar://localhost:6650";
|
||||
private static final String TOPIC_NAME = "test-topic";
|
||||
private static final String SUBSCRIPTION_NAME = "test-subscription";
|
||||
private static final SubscriptionType SUBSCRIPTION_TYPE = SubscriptionType.Exclusive;
|
||||
|
||||
public static void main(String[] args) throws PulsarClientException {
|
||||
PulsarClient client = PulsarClient.builder()
|
||||
.serviceUrl(SERVICE_URL)
|
||||
.build();
|
||||
|
||||
Producer<byte[]> producer = client.newProducer()
|
||||
.topic(TOPIC_NAME)
|
||||
.create();
|
||||
|
||||
ConsumerBuilder<byte[]> consumer1 = client.newConsumer()
|
||||
.topic(TOPIC_NAME)
|
||||
.subscriptionName(SUBSCRIPTION_NAME)
|
||||
.subscriptionType(SUBSCRIPTION_TYPE);
|
||||
|
||||
ConsumerBuilder<byte[]> consumer2 = client.newConsumer()
|
||||
.topic(TOPIC_NAME)
|
||||
.subscriptionName(SUBSCRIPTION_NAME)
|
||||
.subscriptionType(SUBSCRIPTION_TYPE);
|
||||
|
||||
IntStream.range(0, 999).forEach(i -> {
|
||||
Message<byte[]> msg = MessageBuilder.create()
|
||||
.setContent(String.format("message-%d", i).getBytes())
|
||||
.build();
|
||||
try {
|
||||
producer.send(msg);
|
||||
} catch (PulsarClientException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
});
|
||||
|
||||
// Consumer 1 can subscribe to the topic
|
||||
consumer1.subscribe();
|
||||
|
||||
// Consumer 2 cannot due to the exclusive subscription held by consumer 1
|
||||
consumer2.subscribeAsync()
|
||||
.handle((consumer, exception) -> {
|
||||
System.out.println(exception.getMessage());
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
package com.baeldung.pulsar.subscriptions;
|
||||
|
||||
import org.apache.pulsar.client.api.Consumer;
|
||||
import org.apache.pulsar.client.api.ConsumerBuilder;
|
||||
import org.apache.pulsar.client.api.Message;
|
||||
import org.apache.pulsar.client.api.MessageBuilder;
|
||||
import org.apache.pulsar.client.api.Producer;
|
||||
import org.apache.pulsar.client.api.PulsarClient;
|
||||
import org.apache.pulsar.client.api.PulsarClientException;
|
||||
import org.apache.pulsar.client.api.SubscriptionType;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class FailoverSubscriptionUnitTest {
|
||||
private static final String SERVICE_URL = "pulsar://localhost:6650";
|
||||
private static final String TOPIC_NAME = "failover-subscription-test-topic";
|
||||
private static final String SUBSCRIPTION_NAME = "test-subscription";
|
||||
private static final SubscriptionType SUBSCRIPTION_TYPE = SubscriptionType.Failover;
|
||||
private static final int NUM_MSGS = 10;
|
||||
|
||||
public static void main(String[] args) throws PulsarClientException {
|
||||
PulsarClient client = PulsarClient.builder()
|
||||
.serviceUrl(SERVICE_URL)
|
||||
.build();
|
||||
|
||||
Producer<byte[]> producer = client.newProducer()
|
||||
.topic(TOPIC_NAME)
|
||||
.create();
|
||||
|
||||
ConsumerBuilder<byte[]> consumerBuilder = client.newConsumer()
|
||||
.topic(TOPIC_NAME)
|
||||
.subscriptionName(SUBSCRIPTION_NAME)
|
||||
.subscriptionType(SUBSCRIPTION_TYPE);
|
||||
|
||||
Consumer<byte[]> mainConsumer = consumerBuilder
|
||||
.consumerName("consumer-a")
|
||||
.messageListener((consumer, msg) -> {
|
||||
System.out.println("Message received by main consumer");
|
||||
|
||||
try {
|
||||
consumer.acknowledge(msg);
|
||||
} catch (PulsarClientException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
})
|
||||
.subscribe();
|
||||
|
||||
Consumer<byte[]> failoverConsumer = consumerBuilder
|
||||
.consumerName("consumer-b")
|
||||
.messageListener((consumer, msg) -> {
|
||||
System.out.println("Message received by failover consumer");
|
||||
|
||||
try {
|
||||
consumer.acknowledge(msg);
|
||||
} catch (PulsarClientException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
})
|
||||
.subscribe();
|
||||
|
||||
IntStream.range(0, NUM_MSGS).forEach(i -> {
|
||||
Message<byte[]> msg = MessageBuilder.create()
|
||||
.setContent(String.format("message-%d", i).getBytes())
|
||||
.build();
|
||||
try {
|
||||
producer.send(msg);
|
||||
|
||||
Thread.sleep(100);
|
||||
|
||||
if (i > 5) mainConsumer.close();
|
||||
} catch (InterruptedException | PulsarClientException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.solrjava;
|
||||
|
||||
import org.apache.solr.client.solrj.beans.Field;
|
||||
|
||||
public class ProductBean {
|
||||
|
||||
String id;
|
||||
String name;
|
||||
String price;
|
||||
|
||||
public ProductBean(String id, String name, String price) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Field("id")
|
||||
protected void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Field("name")
|
||||
protected void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
@Field("price")
|
||||
protected void setPrice(String price) {
|
||||
this.price = price;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
package com.baeldung.solrjava;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.solr.client.solrj.SolrServerException;
|
||||
import org.apache.solr.client.solrj.impl.HttpSolrClient;
|
||||
import org.apache.solr.client.solrj.impl.XMLResponseParser;
|
||||
import org.apache.solr.common.SolrInputDocument;
|
||||
|
||||
public class SolrJavaIntegration {
|
||||
|
||||
private HttpSolrClient solrClient;
|
||||
|
||||
public SolrJavaIntegration(String clientUrl) {
|
||||
|
||||
solrClient = new HttpSolrClient.Builder(clientUrl).build();
|
||||
solrClient.setParser(new XMLResponseParser());
|
||||
}
|
||||
|
||||
public void addProductBean(ProductBean pBean) throws IOException, SolrServerException {
|
||||
|
||||
solrClient.addBean(pBean);
|
||||
solrClient.commit();
|
||||
}
|
||||
|
||||
public void addSolrDocument(String documentId, String itemName, String itemPrice) throws SolrServerException, IOException {
|
||||
|
||||
SolrInputDocument document = new SolrInputDocument();
|
||||
document.addField("id", documentId);
|
||||
document.addField("name", itemName);
|
||||
document.addField("price", itemPrice);
|
||||
solrClient.add(document);
|
||||
solrClient.commit();
|
||||
}
|
||||
|
||||
public void deleteSolrDocumentById(String documentId) throws SolrServerException, IOException {
|
||||
|
||||
solrClient.deleteById(documentId);
|
||||
solrClient.commit();
|
||||
}
|
||||
|
||||
public void deleteSolrDocumentByQuery(String query) throws SolrServerException, IOException {
|
||||
|
||||
solrClient.deleteByQuery(query);
|
||||
solrClient.commit();
|
||||
}
|
||||
|
||||
protected HttpSolrClient getSolrClient() {
|
||||
return solrClient;
|
||||
}
|
||||
|
||||
protected void setSolrClient(HttpSolrClient solrClient) {
|
||||
this.solrClient = solrClient;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.zookeeper.connection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
import org.apache.zookeeper.WatchedEvent;
|
||||
import org.apache.zookeeper.Watcher;
|
||||
import org.apache.zookeeper.Watcher.Event.KeeperState;
|
||||
import org.apache.zookeeper.ZooKeeper;
|
||||
|
||||
public class ZKConnection {
|
||||
private ZooKeeper zoo;
|
||||
final CountDownLatch connectionLatch = new CountDownLatch(1);
|
||||
|
||||
public ZKConnection() {
|
||||
}
|
||||
|
||||
public ZooKeeper connect(String host) throws IOException, InterruptedException {
|
||||
zoo = new ZooKeeper(host, 2000, new Watcher() {
|
||||
public void process(WatchedEvent we) {
|
||||
if (we.getState() == KeeperState.SyncConnected) {
|
||||
connectionLatch.countDown();
|
||||
}
|
||||
}
|
||||
});
|
||||
connectionLatch.await();
|
||||
return zoo;
|
||||
}
|
||||
|
||||
public void close() throws InterruptedException {
|
||||
zoo.close();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.zookeeper.manager;
|
||||
|
||||
import org.apache.zookeeper.KeeperException;
|
||||
|
||||
public interface ZKManager {
|
||||
/**
|
||||
* Create a Znode and save some data
|
||||
*
|
||||
* @param path
|
||||
* @param data
|
||||
* @throws KeeperException
|
||||
* @throws InterruptedException
|
||||
*/
|
||||
public void create(String path, byte[] data) throws KeeperException, InterruptedException;
|
||||
|
||||
/**
|
||||
* Get ZNode Data
|
||||
*
|
||||
* @param path
|
||||
* @param boolean watchFlag
|
||||
* @throws KeeperException
|
||||
* @throws InterruptedException
|
||||
*/
|
||||
public Object getZNodeData(String path, boolean watchFlag);
|
||||
|
||||
/**
|
||||
* Update the ZNode Data
|
||||
*
|
||||
* @param path
|
||||
* @param data
|
||||
* @throws KeeperException
|
||||
* @throws InterruptedException
|
||||
*/
|
||||
public void update(String path, byte[] data) throws KeeperException, InterruptedException, KeeperException;
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.zookeeper.manager;
|
||||
|
||||
import org.apache.zookeeper.CreateMode;
|
||||
import org.apache.zookeeper.KeeperException;
|
||||
import org.apache.zookeeper.ZooDefs;
|
||||
import org.apache.zookeeper.ZooKeeper;
|
||||
|
||||
import com.baeldung.zookeeper.connection.ZKConnection;
|
||||
|
||||
public class ZKManagerImpl implements ZKManager {
|
||||
private static ZooKeeper zkeeper;
|
||||
private static ZKConnection zkConnection;
|
||||
|
||||
public ZKManagerImpl() {
|
||||
initialize();
|
||||
}
|
||||
|
||||
/** * Initialize connection */
|
||||
private void initialize() {
|
||||
try {
|
||||
zkConnection = new ZKConnection();
|
||||
zkeeper = zkConnection.connect("localhost");
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void closeConnection() {
|
||||
try {
|
||||
zkConnection.close();
|
||||
} catch (InterruptedException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void create(String path, byte[] data) throws KeeperException, InterruptedException {
|
||||
zkeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
|
||||
}
|
||||
|
||||
public Object getZNodeData(String path, boolean watchFlag) {
|
||||
try {
|
||||
byte[] b = null;
|
||||
b = zkeeper.getData(path, null, null);
|
||||
String data = new String(b, "UTF-8");
|
||||
System.out.println(data);
|
||||
return data;
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void update(String path, byte[] data) throws KeeperException, InterruptedException {
|
||||
int version = zkeeper.exists(path, true)
|
||||
.getVersion();
|
||||
zkeeper.setData(path, data, version);
|
||||
}
|
||||
}
|
|
@ -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>
|
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.apache.beam.intro;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.apache.beam.intro.WordCount;
|
||||
|
||||
public class WordCountUnitTest {
|
||||
|
||||
@Test
|
||||
// @Ignore
|
||||
public void givenInputFile_whenWordCountRuns_thenJobFinishWithoutError() {
|
||||
boolean jobDone = WordCount.wordCount("src/test/resources/wordcount.txt", "target/output");
|
||||
assertTrue(jobDone);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.apache.curator;
|
||||
|
||||
import org.apache.curator.RetryPolicy;
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.framework.CuratorFrameworkFactory;
|
||||
import org.apache.curator.retry.RetryNTimes;
|
||||
import org.junit.Before;
|
||||
|
||||
public abstract class BaseManualTest {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
org.apache.log4j.BasicConfigurator.configure();
|
||||
}
|
||||
|
||||
protected CuratorFramework newClient() {
|
||||
int sleepMsBetweenRetries = 100;
|
||||
int maxRetries = 3;
|
||||
RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries);
|
||||
return CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
package com.baeldung.apache.curator.configuration;
|
||||
|
||||
import static com.jayway.awaitility.Awaitility.await;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.x.async.AsyncCuratorFramework;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.apache.curator.BaseManualTest;
|
||||
|
||||
public class ConfigurationManagementManualTest extends BaseManualTest {
|
||||
|
||||
private static final String KEY_FORMAT = "/%s";
|
||||
|
||||
@Test
|
||||
public void givenPath_whenCreateKey_thenValueIsStored() throws Exception {
|
||||
try (CuratorFramework client = newClient()) {
|
||||
client.start();
|
||||
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
|
||||
String key = getKey();
|
||||
String expected = "my_value";
|
||||
|
||||
// Create key nodes structure
|
||||
client.create()
|
||||
.forPath(key);
|
||||
|
||||
// Set data value for our key
|
||||
async.setData()
|
||||
.forPath(key, expected.getBytes());
|
||||
|
||||
// Get data value
|
||||
AtomicBoolean isEquals = new AtomicBoolean();
|
||||
async.getData()
|
||||
.forPath(key)
|
||||
.thenAccept(
|
||||
data -> isEquals.set(new String(data).equals(expected)));
|
||||
|
||||
await().until(() -> assertThat(isEquals.get()).isTrue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenWatchAKeyAndStoreAValue_thenWatcherIsTriggered()
|
||||
throws Exception {
|
||||
try (CuratorFramework client = newClient()) {
|
||||
client.start();
|
||||
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
|
||||
String key = getKey();
|
||||
String expected = "my_value";
|
||||
|
||||
// Create key structure
|
||||
async.create()
|
||||
.forPath(key);
|
||||
|
||||
List<String> changes = new ArrayList<>();
|
||||
|
||||
// Watch data value
|
||||
async.watched()
|
||||
.getData()
|
||||
.forPath(key)
|
||||
.event()
|
||||
.thenAccept(watchedEvent -> {
|
||||
try {
|
||||
changes.add(new String(client.getData()
|
||||
.forPath(watchedEvent.getPath())));
|
||||
} catch (Exception e) {
|
||||
// fail ...
|
||||
}
|
||||
});
|
||||
|
||||
// Set data value for our key
|
||||
async.setData()
|
||||
.forPath(key, expected.getBytes());
|
||||
|
||||
await().until(() -> assertThat(changes.size() > 0).isTrue());
|
||||
}
|
||||
}
|
||||
|
||||
private String getKey() {
|
||||
return String.format(KEY_FORMAT, UUID.randomUUID()
|
||||
.toString());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
package com.baeldung.apache.curator.connection;
|
||||
|
||||
import static com.jayway.awaitility.Awaitility.await;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import org.apache.curator.RetryPolicy;
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.framework.CuratorFrameworkFactory;
|
||||
import org.apache.curator.retry.RetryNTimes;
|
||||
import org.apache.curator.x.async.AsyncCuratorFramework;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ConnectionManagementManualTest {
|
||||
|
||||
@Test
|
||||
public void givenRunningZookeeper_whenOpenConnection_thenClientIsOpened()
|
||||
throws Exception {
|
||||
int sleepMsBetweenRetries = 100;
|
||||
int maxRetries = 3;
|
||||
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
|
||||
sleepMsBetweenRetries);
|
||||
|
||||
try (CuratorFramework client = CuratorFrameworkFactory
|
||||
.newClient("127.0.0.1:2181", retryPolicy)) {
|
||||
client.start();
|
||||
|
||||
assertThat(client.checkExists()
|
||||
.forPath("/")).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningZookeeper_whenOpenConnectionUsingAsyncNotBlocking_thenClientIsOpened()
|
||||
throws InterruptedException {
|
||||
int sleepMsBetweenRetries = 100;
|
||||
int maxRetries = 3;
|
||||
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
|
||||
sleepMsBetweenRetries);
|
||||
|
||||
try (CuratorFramework client = CuratorFrameworkFactory
|
||||
.newClient("127.0.0.1:2181", retryPolicy)) {
|
||||
client.start();
|
||||
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
|
||||
|
||||
AtomicBoolean exists = new AtomicBoolean(false);
|
||||
|
||||
async.checkExists()
|
||||
.forPath("/")
|
||||
.thenAcceptAsync(s -> exists.set(s != null));
|
||||
|
||||
await().until(() -> assertThat(exists.get()).isTrue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningZookeeper_whenOpenConnectionUsingAsyncBlocking_thenClientIsOpened()
|
||||
throws InterruptedException {
|
||||
int sleepMsBetweenRetries = 100;
|
||||
int maxRetries = 3;
|
||||
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
|
||||
sleepMsBetweenRetries);
|
||||
|
||||
try (CuratorFramework client = CuratorFrameworkFactory
|
||||
.newClient("127.0.0.1:2181", retryPolicy)) {
|
||||
client.start();
|
||||
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
|
||||
|
||||
AtomicBoolean exists = new AtomicBoolean(false);
|
||||
|
||||
async.checkExists()
|
||||
.forPath("/")
|
||||
.thenAccept(s -> exists.set(s != null));
|
||||
|
||||
await().until(() -> assertThat(exists.get()).isTrue());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.apache.curator.modeled;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.x.async.AsyncCuratorFramework;
|
||||
import org.apache.curator.x.async.modeled.JacksonModelSerializer;
|
||||
import org.apache.curator.x.async.modeled.ModelSpec;
|
||||
import org.apache.curator.x.async.modeled.ModeledFramework;
|
||||
import org.apache.curator.x.async.modeled.ZPath;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.apache.curator.BaseManualTest;
|
||||
|
||||
public class ModelTypedExamplesManualTest extends BaseManualTest {
|
||||
|
||||
@Test
|
||||
public void givenPath_whenStoreAModel_thenNodesAreCreated()
|
||||
throws InterruptedException {
|
||||
|
||||
ModelSpec<HostConfig> mySpec = ModelSpec
|
||||
.builder(ZPath.parseWithIds("/config/dev"),
|
||||
JacksonModelSerializer.build(HostConfig.class))
|
||||
.build();
|
||||
|
||||
try (CuratorFramework client = newClient()) {
|
||||
client.start();
|
||||
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
|
||||
ModeledFramework<HostConfig> modeledClient = ModeledFramework
|
||||
.wrap(async, mySpec);
|
||||
|
||||
modeledClient.set(new HostConfig("host-name", 8080));
|
||||
|
||||
modeledClient.read()
|
||||
.whenComplete((value, e) -> {
|
||||
if (e != null) {
|
||||
fail("Cannot read host config", e);
|
||||
} else {
|
||||
assertThat(value).isNotNull();
|
||||
assertThat(value.getHostname()).isEqualTo("host-name");
|
||||
assertThat(value.getPort()).isEqualTo(8080);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
package com.baeldung.apache.curator.recipes;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.framework.recipes.leader.LeaderSelector;
|
||||
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
|
||||
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
|
||||
import org.apache.curator.framework.recipes.shared.SharedCount;
|
||||
import org.apache.curator.framework.state.ConnectionState;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.apache.curator.BaseManualTest;
|
||||
|
||||
public class RecipesManualTest extends BaseManualTest {
|
||||
|
||||
@Test
|
||||
public void givenRunningZookeeper_whenUsingLeaderElection_thenNoErrors() {
|
||||
try (CuratorFramework client = newClient()) {
|
||||
client.start();
|
||||
LeaderSelector leaderSelector = new LeaderSelector(client, "/mutex/select/leader/for/job/A", new LeaderSelectorListener() {
|
||||
|
||||
@Override
|
||||
public void stateChanged(CuratorFramework client, ConnectionState newState) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void takeLeadership(CuratorFramework client) throws Exception {
|
||||
// I'm the leader of the job A !
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
leaderSelector.start();
|
||||
|
||||
// Wait until the job A is done among all the members
|
||||
|
||||
leaderSelector.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningZookeeper_whenUsingSharedLock_thenNoErrors() throws Exception {
|
||||
try (CuratorFramework client = newClient()) {
|
||||
client.start();
|
||||
InterProcessSemaphoreMutex sharedLock = new InterProcessSemaphoreMutex(client, "/mutex/process/A");
|
||||
|
||||
sharedLock.acquire();
|
||||
|
||||
// Do process A
|
||||
|
||||
sharedLock.release();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningZookeeper_whenUsingSharedCounter_thenCounterIsIncrement() throws Exception {
|
||||
try (CuratorFramework client = newClient()) {
|
||||
client.start();
|
||||
|
||||
try (SharedCount counter = new SharedCount(client, "/counters/A", 0)) {
|
||||
counter.start();
|
||||
|
||||
counter.setCount(0);
|
||||
counter.setCount(counter.getCount() + 1);
|
||||
|
||||
assertThat(counter.getCount()).isEqualTo(1);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.chunker.ChunkerME;
|
||||
import opennlp.tools.chunker.ChunkerModel;
|
||||
import opennlp.tools.postag.POSModel;
|
||||
import opennlp.tools.postag.POSTaggerME;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ChunkerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenChunkerModel_whenChunk_thenChunksAreDetected() throws Exception {
|
||||
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("He reckons the current account deficit will narrow to only 8 billion.");
|
||||
|
||||
InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin");
|
||||
POSModel posModel = new POSModel(inputStreamPOSTagger);
|
||||
POSTaggerME posTagger = new POSTaggerME(posModel);
|
||||
String tags[] = posTagger.tag(tokens);
|
||||
|
||||
InputStream inputStreamChunker = new FileInputStream("src/main/resources/models/en-chunker.bin");
|
||||
ChunkerModel chunkerModel = new ChunkerModel(inputStreamChunker);
|
||||
ChunkerME chunker = new ChunkerME(chunkerModel);
|
||||
String[] chunks = chunker.chunk(tokens, tags);
|
||||
assertThat(chunks).contains("B-NP", "B-VP", "B-NP", "I-NP", "I-NP", "I-NP", "B-VP", "I-VP", "B-PP", "B-NP", "I-NP", "I-NP", "O");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import opennlp.tools.langdetect.Language;
|
||||
import opennlp.tools.langdetect.LanguageDetector;
|
||||
import opennlp.tools.langdetect.LanguageDetectorFactory;
|
||||
import opennlp.tools.langdetect.LanguageDetectorME;
|
||||
import opennlp.tools.langdetect.LanguageDetectorModel;
|
||||
import opennlp.tools.langdetect.LanguageDetectorSampleStream;
|
||||
import opennlp.tools.util.InputStreamFactory;
|
||||
import opennlp.tools.util.MarkableFileInputStreamFactory;
|
||||
import opennlp.tools.util.ObjectStream;
|
||||
import opennlp.tools.util.PlainTextByLineStream;
|
||||
import opennlp.tools.util.TrainingParameters;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.tuple;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LanguageDetectorAndTrainingDataUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLanguageDictionary_whenLanguageDetect_thenLanguageIsDetected() throws FileNotFoundException, IOException {
|
||||
InputStreamFactory dataIn = new MarkableFileInputStreamFactory(new File("src/main/resources/models/DoccatSample.txt"));
|
||||
ObjectStream lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
|
||||
LanguageDetectorSampleStream sampleStream = new LanguageDetectorSampleStream(lineStream);
|
||||
TrainingParameters params = new TrainingParameters();
|
||||
params.put(TrainingParameters.ITERATIONS_PARAM, 100);
|
||||
params.put(TrainingParameters.CUTOFF_PARAM, 5);
|
||||
params.put("DataIndexer", "TwoPass");
|
||||
params.put(TrainingParameters.ALGORITHM_PARAM, "NAIVEBAYES");
|
||||
|
||||
LanguageDetectorModel model = LanguageDetectorME.train(sampleStream, params, new LanguageDetectorFactory());
|
||||
|
||||
LanguageDetector ld = new LanguageDetectorME(model);
|
||||
Language[] languages = ld.predictLanguages("estava em uma marcenaria na Rua Bruno");
|
||||
|
||||
assertThat(Arrays.asList(languages)).extracting("lang", "confidence").contains(tuple("pob", 0.9999999950605625),
|
||||
tuple("ita", 4.939427661577956E-9), tuple("spa", 9.665954064665144E-15),
|
||||
tuple("fra", 8.250349924885834E-25));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.lemmatizer.DictionaryLemmatizer;
|
||||
import opennlp.tools.postag.POSModel;
|
||||
import opennlp.tools.postag.POSTaggerME;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LemmetizerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEnglishDictionary_whenLemmatize_thenLemmasAreDetected() throws Exception {
|
||||
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("John has a sister named Penny.");
|
||||
|
||||
InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin");
|
||||
POSModel posModel = new POSModel(inputStreamPOSTagger);
|
||||
POSTaggerME posTagger = new POSTaggerME(posModel);
|
||||
String tags[] = posTagger.tag(tokens);
|
||||
InputStream dictLemmatizer = getClass().getResourceAsStream("/models/en-lemmatizer.dict");
|
||||
DictionaryLemmatizer lemmatizer = new DictionaryLemmatizer(dictLemmatizer);
|
||||
String[] lemmas = lemmatizer.lemmatize(tokens, tags);
|
||||
|
||||
assertThat(lemmas).contains("O", "have", "a", "sister", "name", "O", "O");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import opennlp.tools.namefind.NameFinderME;
|
||||
import opennlp.tools.namefind.TokenNameFinderModel;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import opennlp.tools.util.Span;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NamedEntityRecognitionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEnglishPersonModel_whenNER_thenPersonsAreDetected() throws Exception {
|
||||
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("John is 26 years old. His best friend's name is Leonard. He has a sister named Penny.");
|
||||
|
||||
InputStream inputStreamNameFinder = getClass().getResourceAsStream("/models/en-ner-person.bin");
|
||||
TokenNameFinderModel model = new TokenNameFinderModel(inputStreamNameFinder);
|
||||
NameFinderME nameFinderME = new NameFinderME(model);
|
||||
List<Span> spans = Arrays.asList(nameFinderME.find(tokens));
|
||||
assertThat(spans.toString()).isEqualTo("[[0..1) person, [13..14) person, [20..21) person]");
|
||||
List<String> names = new ArrayList<String>();
|
||||
int k = 0;
|
||||
for (Span s : spans) {
|
||||
names.add("");
|
||||
for (int index = s.getStart(); index < s.getEnd(); index++) {
|
||||
names.set(k, names.get(k) + tokens[index]);
|
||||
}
|
||||
k++;
|
||||
}
|
||||
assertThat(names).contains("John","Leonard","Penny");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.postag.POSModel;
|
||||
import opennlp.tools.postag.POSTaggerME;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class POSTaggerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenPOSModel_whenPOSTagging_thenPOSAreDetected() throws Exception {
|
||||
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("John has a sister named Penny.");
|
||||
|
||||
InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin");
|
||||
POSModel posModel = new POSModel(inputStreamPOSTagger);
|
||||
POSTaggerME posTagger = new POSTaggerME(posModel);
|
||||
String tags[] = posTagger.tag(tokens);
|
||||
assertThat(tags).contains("NNP", "VBZ", "DT", "NN", "VBN", "NNP", ".");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.sentdetect.SentenceDetectorME;
|
||||
import opennlp.tools.sentdetect.SentenceModel;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SentenceDetectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEnglishModel_whenDetect_thenSentencesAreDetected() throws Exception {
|
||||
|
||||
String paragraph = "This is a statement. This is another statement. Now is an abstract word for time, "
|
||||
+ "that is always flying. And my email address is google@gmail.com.";
|
||||
|
||||
InputStream is = getClass().getResourceAsStream("/models/en-sent.bin");
|
||||
SentenceModel model = new SentenceModel(is);
|
||||
|
||||
SentenceDetectorME sdetector = new SentenceDetectorME(model);
|
||||
|
||||
String sentences[] = sdetector.sentDetect(paragraph);
|
||||
assertThat(sentences).contains("This is a statement.",
|
||||
"This is another statement.",
|
||||
"Now is an abstract word for time, that is always flying.",
|
||||
"And my email address is google@gmail.com.");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import opennlp.tools.tokenize.TokenizerME;
|
||||
import opennlp.tools.tokenize.TokenizerModel;
|
||||
import opennlp.tools.tokenize.WhitespaceTokenizer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TokenizerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEnglishModel_whenTokenize_thenTokensAreDetected() throws Exception {
|
||||
InputStream inputStream = getClass().getResourceAsStream("/models/en-token.bin");
|
||||
TokenizerModel model = new TokenizerModel(inputStream);
|
||||
TokenizerME tokenizer = new TokenizerME(model);
|
||||
String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource.");
|
||||
assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource", ".");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhitespaceTokenizer_whenTokenize_thenTokensAreDetected() throws Exception {
|
||||
WhitespaceTokenizer tokenizer = WhitespaceTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource.");
|
||||
assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSimpleTokenizer_whenTokenize_thenTokensAreDetected() throws Exception {
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource.");
|
||||
assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource", ".");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
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 AvroSerealizerDeSerealizerUnitTest {
|
||||
|
||||
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 WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() {
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
|
||||
assertTrue(Objects.nonNull(data));
|
||||
assertTrue(data.length > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() {
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
|
||||
assertTrue(Objects.nonNull(data));
|
||||
assertTrue(data.length > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() {
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
|
||||
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
|
||||
assertEquals(actualRequest, request);
|
||||
assertTrue(actualRequest.getRequestTime()
|
||||
.equals(request.getRequestTime()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() {
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
|
||||
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
|
||||
assertEquals(actualRequest, request);
|
||||
assertTrue(actualRequest.getRequestTime()
|
||||
.equals(request.getRequestTime()));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
package com.baeldung.bval.validation;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import javax.validation.ValidatorFactory;
|
||||
|
||||
import org.apache.bval.jsr.ApacheValidationProvider;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.bval.model.User;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ValidationIntegrationTest {
|
||||
private static ValidatorFactory validatorFactory;
|
||||
private static Validator validator;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
validatorFactory = Validation.byProvider(ApacheValidationProvider.class)
|
||||
.configure()
|
||||
.buildValidatorFactory();
|
||||
validator = validatorFactory.getValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUser_whenValidate_thenValidationViolations() {
|
||||
User user = new User("ana@yahoo.com", "pass", "nameTooLong_______________", 15);
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertTrue("no violations", violations.size() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidAge_whenValidateProperty_thenConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 12);
|
||||
|
||||
Set<ConstraintViolation<User>> propertyViolations = validator.validateProperty(user, "age");
|
||||
assertEquals("size is not 1", 1, propertyViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidAge_whenValidateValue_thenNoConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 18);
|
||||
|
||||
Set<ConstraintViolation<User>> valueViolations = validator.validateValue(User.class, "age", 20);
|
||||
assertEquals("size is not 0", 0, valueViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidateNonJSR_thenCorrect() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 20);
|
||||
user.setCardNumber("1234");
|
||||
user.setIban("1234");
|
||||
user.setWebsite("10.0.2.50");
|
||||
user.setMainDirectory(new File("."));
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "iban");
|
||||
assertEquals("size is not 1", 1, violations.size());
|
||||
|
||||
violations = validator.validateProperty(user, "website");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
|
||||
violations = validator.validateProperty(user, "mainDirectory");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidPassword_whenValidatePassword_thenConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "password", "Ana", 20);
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "password");
|
||||
assertEquals("message incorrect", "Invalid password", violations.iterator()
|
||||
.next()
|
||||
.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidPassword_whenValidatePassword_thenNoConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "password#", "Ana", 20);
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "password");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void close() {
|
||||
if (validatorFactory != null) {
|
||||
validatorFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
package com.baeldung.geode;
|
||||
|
||||
import com.baeldung.geode.functions.UpperCaseNames;
|
||||
import org.apache.geode.cache.Region;
|
||||
import org.apache.geode.cache.client.ClientCache;
|
||||
import org.apache.geode.cache.client.ClientCacheFactory;
|
||||
import org.apache.geode.cache.client.ClientRegionShortcut;
|
||||
import org.apache.geode.cache.execute.Execution;
|
||||
import org.apache.geode.cache.execute.FunctionService;
|
||||
import org.apache.geode.cache.query.*;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class GeodeSamplesLiveTest {
|
||||
|
||||
ClientCache cache = null;
|
||||
Region<String, String> region = null;
|
||||
Region<Integer, Customer> queryRegion = null;
|
||||
Region<CustomerKey, Customer> customerRegion = null;
|
||||
|
||||
@Before
|
||||
public void connect() {
|
||||
this.cache = new ClientCacheFactory().addPoolLocator("localhost", 10334)
|
||||
.create();
|
||||
this.region = this.cache.<String, String> createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
|
||||
.create("baeldung");
|
||||
this.customerRegion = this.cache.<CustomerKey, Customer> createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
|
||||
.create("baeldung-customers");
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
this.cache.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendMessageToRegion_thenMessageSavedSuccessfully() {
|
||||
|
||||
this.region.put("1", "Hello");
|
||||
this.region.put("2", "Baeldung");
|
||||
|
||||
assertEquals("Hello", region.get("1"));
|
||||
assertEquals("Baeldung", region.get("2"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPutMultipleValuesAtOnce_thenValuesSavedSuccessfully() {
|
||||
|
||||
Supplier<Stream<String>> keys = () -> Stream.of("A", "B", "C", "D", "E");
|
||||
Map<String, String> values = keys.get()
|
||||
.collect(Collectors.toMap(Function.identity(), String::toLowerCase));
|
||||
|
||||
this.region.putAll(values);
|
||||
|
||||
keys.get()
|
||||
.forEach(k -> assertEquals(k.toLowerCase(), this.region.get(k)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPutCustomKey_thenValuesSavedSuccessfully() {
|
||||
CustomerKey key = new CustomerKey(123);
|
||||
Customer customer = new Customer(key, "William", "Russell", 35);
|
||||
|
||||
Map<CustomerKey, Customer> customerInfo = new HashMap<>();
|
||||
customerInfo.put(key, customer);
|
||||
|
||||
this.customerRegion.putAll(customerInfo);
|
||||
|
||||
Customer storedCustomer = this.customerRegion.get(key);
|
||||
assertEquals("William", storedCustomer.getFirstName());
|
||||
assertEquals("Russell", storedCustomer.getLastName());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindACustomerUsingOQL_thenCorrectCustomerObject() throws NameResolutionException, TypeMismatchException, QueryInvocationTargetException, FunctionDomainException {
|
||||
|
||||
Map<CustomerKey, Customer> data = new HashMap<>();
|
||||
data.put(new CustomerKey(1), new Customer("Gheorge", "Manuc", 36));
|
||||
data.put(new CustomerKey(2), new Customer("Allan", "McDowell", 43));
|
||||
this.customerRegion.putAll(data);
|
||||
|
||||
QueryService queryService = this.cache.getQueryService();
|
||||
String query = "select * from /baeldung-customers c where c.firstName = 'Allan'";
|
||||
SelectResults<Customer> queryResults = (SelectResults<Customer>) queryService.newQuery(query)
|
||||
.execute();
|
||||
assertEquals(1, queryResults.size());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExecuteUppercaseNames_thenCustomerNamesAreUppercased() {
|
||||
Execution execution = FunctionService.onRegion(this.customerRegion);
|
||||
execution.execute(UpperCaseNames.class.getName());
|
||||
Customer customer = this.customerRegion.get(new CustomerKey(1));
|
||||
assertEquals("GHEORGE", customer.getFirstName());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.meecrowave;
|
||||
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.meecrowave.Meecrowave;
|
||||
import org.apache.meecrowave.junit.MonoMeecrowave;
|
||||
import org.apache.meecrowave.testing.ConfigurationInject;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
@RunWith(MonoMeecrowave.Runner.class)
|
||||
public class ArticleEndpointsUnitTest {
|
||||
|
||||
@ConfigurationInject
|
||||
private Meecrowave.Builder config;
|
||||
private static OkHttpClient client;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRetunedArticle_thenCorrect() throws IOException {
|
||||
final String base = "http://localhost:"+config.getHttpPort();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(base+"/article")
|
||||
.build();
|
||||
Response response = client.newCall(request).execute();
|
||||
assertEquals(200, response.code());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,108 @@
|
|||
package com.baeldung.solrjava;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.solr.client.solrj.SolrQuery;
|
||||
import org.apache.solr.client.solrj.SolrServerException;
|
||||
import org.apache.solr.client.solrj.response.QueryResponse;
|
||||
import org.apache.solr.common.SolrDocument;
|
||||
import org.apache.solr.common.SolrDocumentList;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SolrJavaLiveTest {
|
||||
|
||||
private SolrJavaIntegration solrJavaIntegration;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
|
||||
solrJavaIntegration = new SolrJavaIntegration("http://localhost:8983/solr/bigboxstore");
|
||||
solrJavaIntegration.addSolrDocument("123456", "Kenmore Dishwasher", "599.99");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdd_thenVerifyAddedByQueryOnId() throws SolrServerException, IOException {
|
||||
|
||||
SolrQuery query = new SolrQuery();
|
||||
query.set("q", "id:123456");
|
||||
QueryResponse response = null;
|
||||
|
||||
response = solrJavaIntegration.getSolrClient().query(query);
|
||||
|
||||
SolrDocumentList docList = response.getResults();
|
||||
assertEquals(1, docList.getNumFound());
|
||||
|
||||
for (SolrDocument doc : docList) {
|
||||
assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name"));
|
||||
assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdd_thenVerifyAddedByQueryOnPrice() throws SolrServerException, IOException {
|
||||
|
||||
SolrQuery query = new SolrQuery();
|
||||
query.set("q", "price:599.99");
|
||||
QueryResponse response = null;
|
||||
|
||||
response = solrJavaIntegration.getSolrClient().query(query);
|
||||
|
||||
SolrDocumentList docList = response.getResults();
|
||||
assertEquals(1, docList.getNumFound());
|
||||
|
||||
for (SolrDocument doc : docList) {
|
||||
assertEquals("123456", (String) doc.getFieldValue("id"));
|
||||
assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdd_thenVerifyAddedByQuery() throws SolrServerException, IOException {
|
||||
|
||||
SolrDocument doc = solrJavaIntegration.getSolrClient().getById("123456");
|
||||
assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name"));
|
||||
assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddBean_thenVerifyAddedByQuery() throws SolrServerException, IOException {
|
||||
|
||||
ProductBean pBean = new ProductBean("888", "Apple iPhone 6s", "299.99");
|
||||
solrJavaIntegration.addProductBean(pBean);
|
||||
|
||||
SolrDocument doc = solrJavaIntegration.getSolrClient().getById("888");
|
||||
assertEquals("Apple iPhone 6s", (String) doc.getFieldValue("name"));
|
||||
assertEquals((Double) 299.99, (Double) doc.getFieldValue("price"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeleteById_thenVerifyDeleted() throws SolrServerException, IOException {
|
||||
|
||||
solrJavaIntegration.deleteSolrDocumentById("123456");
|
||||
|
||||
SolrQuery query = new SolrQuery();
|
||||
query.set("q", "id:123456");
|
||||
QueryResponse response = solrJavaIntegration.getSolrClient().query(query);
|
||||
|
||||
SolrDocumentList docList = response.getResults();
|
||||
assertEquals(0, docList.getNumFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeleteByQuery_thenVerifyDeleted() throws SolrServerException, IOException {
|
||||
|
||||
solrJavaIntegration.deleteSolrDocumentByQuery("name:Kenmore Dishwasher");
|
||||
|
||||
SolrQuery query = new SolrQuery();
|
||||
query.set("q", "id:123456");
|
||||
QueryResponse response = null;
|
||||
|
||||
response = solrJavaIntegration.getSolrClient().query(query);
|
||||
|
||||
SolrDocumentList docList = response.getResults();
|
||||
assertEquals(0, docList.getNumFound());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
We've all heard the scare stories about North Korea: the homemade nuclear arsenal built while their people starve and then aimed imprecisely at the rest of the world, a
|
||||
leader so deluded he makes L Ron Hubbard look like a man excessively overburdened with self-doubt and their deep-seated belief that foreign capitalists will invade at any
|
||||
moment and steal all their bauxite.
|
||||
The popular portrayal of this Marxist nation is something like one of the more harrowing episodes of M*A*S*H, only with the cast of wacky characters replaced by twitchy,
|
||||
heavily armed Stalinist meth addicts
|
||||
Cracked would like to take a moment to celebrate the good things about North Korea though, the things that the country's enemies prefer to suppress as part of their politically
|
||||
motivated jealousy. Like how no different to you and me, there's nothing every North Korean likes more after an 18 hour shift at the phosphorus plant than a nice beer to go with
|
||||
his dried fish ration. Ever attentive to its people's needs and in the twinkling of a decade, North Korea's leadership bought, disassembled, transported and rebuilt a British
|
||||
brewery in order to discover and reproduce the secrets of beer and then brew the sweet nectar for its hardworking people, up to 18 bottles at a time. And with minimal fatalities.
|
||||
When was the last time YOUR leader got a beer for YOU, American? (NB do not answer this question if you are Henry Louis Gates).
|
||||
Or how about the fried chicken restaurant that downtown Pyongyang boasts? Yes real chicken, fried and then delivered to your sleeping cube, with optional beer if you like! You
|
||||
don't even have to remove the feathers or pull out the gizzard yourself. Mostly. Americans must eat their fried chicken from a bucket, like swine, sold by a company so secretive
|
||||
that even the very blend of seasoning used is intentionally kept from them. And they call North Korea paranoid?
|
||||
And how many nations would entertain the syphilitic, bourgeois ramblings of Bill Clinton let alone permit him anywhere near their proud womenfolk? Only wise Kim Jong Il could see
|
||||
past Bill's many, many imperfections and treat him with the pity and kindness he deserves, accepting his feeble pleas to pardon the American spies rightly convicted of photographing
|
||||
the nation's sensitive beetroot fields.
|
Loading…
Reference in New Issue