net.mguenther.kafka.junit.SendKeyValues Maven / Gradle / Ivy
package net.mguenther.kafka.junit;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;
@Getter
@ToString
@RequiredArgsConstructor
public class SendKeyValues {
public static class SendKeyValuesBuilder {
private final String topic;
private final Collection> records = new ArrayList<>();
private final Properties producerProps = new Properties();
SendKeyValuesBuilder(final String topic, final Collection> records) {
this.topic = topic;
this.records.addAll(records);
}
public SendKeyValuesBuilder with(final String propertyName, final T value) {
producerProps.put(propertyName, value);
return this;
}
public SendKeyValuesBuilder withAll(final Properties producerProps) {
this.producerProps.putAll(producerProps);
return this;
}
private void ifNonExisting(final String propertyName, final T value) {
if (producerProps.get(propertyName) != null) return;
producerProps.put(propertyName, value);
}
public SendKeyValues useDefaults() {
producerProps.clear();
return build();
}
public SendKeyValues build() {
ifNonExisting(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
ifNonExisting(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
ifNonExisting(ProducerConfig.ACKS_CONFIG, "all");
ifNonExisting(ProducerConfig.RETRIES_CONFIG, "1");
return new SendKeyValues<>(topic, records, producerProps);
}
}
private final String topic;
private final Collection> records;
private final Properties producerProps;
public static SendKeyValuesBuilder to(final String topic, final Collection> records) {
return new SendKeyValuesBuilder<>(topic, records);
}
}