[BAEL-16003] Moving article out of libraries (& flink from libraries-data) into libraries-data-2
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
### Relevant articles
|
||||
- [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink)
|
||||
- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog)
|
||||
- [Introduction to Conflict-Free Replicated Data Types](http://www.baeldung.com/java-conflict-free-replicated-data-types)
|
||||
- [Introduction to javax.measure](http://www.baeldung.com/javax-measure)
|
||||
- [Introduction To Docx4J](http://www.baeldung.com/docx4j)
|
||||
- [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client)
|
||||
- [Introduction To OpenCSV](http://www.baeldung.com/opencsv)
|
||||
- [Introduction to Smooks](http://www.baeldung.com/smooks)
|
||||
- [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
log4j.rootLogger=INFO, stdout
|
||||
@@ -0,0 +1,128 @@
|
||||
<?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>libraries-http</artifactId>
|
||||
<name>libraries-http</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.flink</groupId>
|
||||
<artifactId>flink-connector-kafka-0.11_2.11</artifactId>
|
||||
<version>${flink.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.flink</groupId>
|
||||
<artifactId>flink-streaming-java_2.11</artifactId>
|
||||
<version>${flink.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.flink</groupId>
|
||||
<artifactId>flink-core</artifactId>
|
||||
<version>${flink.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.flink</groupId>
|
||||
<artifactId>flink-java</artifactId>
|
||||
<version>${flink.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.flink</groupId>
|
||||
<artifactId>flink-test-utils_2.11</artifactId>
|
||||
<version>${flink.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.agkn</groupId>
|
||||
<artifactId>hll</artifactId>
|
||||
<version>${hll.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.netopyr.wurmloch</groupId>
|
||||
<artifactId>wurmloch-crdt</artifactId>
|
||||
<version>${crdt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>tec.units</groupId>
|
||||
<artifactId>unit-ri</artifactId>
|
||||
<version>${unit-ri.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<version>${jaxb-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.docx4j</groupId>
|
||||
<artifactId>docx4j</artifactId>
|
||||
<version>${docx4j.version}</version>
|
||||
</dependency>
|
||||
<!-- google api -->
|
||||
<dependency>
|
||||
<groupId>com.google.api-client</groupId>
|
||||
<artifactId>google-api-client</artifactId>
|
||||
<version>${google-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.oauth-client</groupId>
|
||||
<artifactId>google-oauth-client-jetty</artifactId>
|
||||
<version>${google-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.apis</groupId>
|
||||
<artifactId>google-api-services-sheets</artifactId>
|
||||
<version>${google-sheets.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.opencsv/opencsv -->
|
||||
<dependency>
|
||||
<groupId>com.opencsv</groupId>
|
||||
<artifactId>opencsv</artifactId>
|
||||
<version>${opencsv.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.milyn</groupId>
|
||||
<artifactId>milyn-smooks-all</artifactId>
|
||||
<version>${smooks.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.infinispan</groupId>
|
||||
<artifactId>infinispan-core</artifactId>
|
||||
<version>${infinispan.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<flink.version>1.5.0</flink.version>
|
||||
<hll.version>1.6.0</hll.version>
|
||||
<crdt.version>0.1.0</crdt.version>
|
||||
<unit-ri.version>1.0.3</unit-ri.version>
|
||||
<docx4j.version>3.3.5</docx4j.version>
|
||||
<jaxb-api.version>2.1</jaxb-api.version>
|
||||
<google-api.version>1.23.0</google-api.version>
|
||||
<opencsv.version>4.1</opencsv.version>
|
||||
<smooks.version>1.7.0</smooks.version>
|
||||
<infinispan.version>9.1.5.Final</infinispan.version>
|
||||
<google-sheets.version>v4-rev493-1.21.0</google-sheets.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.baeldung.docx;
|
||||
|
||||
import org.docx4j.dml.wordprocessingDrawing.Inline;
|
||||
import org.docx4j.jaxb.Context;
|
||||
import org.docx4j.model.table.TblFactory;
|
||||
import org.docx4j.openpackaging.exceptions.Docx4JException;
|
||||
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
|
||||
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
|
||||
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
|
||||
import org.docx4j.wml.BooleanDefaultTrue;
|
||||
import org.docx4j.wml.Color;
|
||||
import org.docx4j.wml.Drawing;
|
||||
import org.docx4j.wml.ObjectFactory;
|
||||
import org.docx4j.wml.P;
|
||||
import org.docx4j.wml.R;
|
||||
import org.docx4j.wml.RPr;
|
||||
import org.docx4j.wml.Tbl;
|
||||
import org.docx4j.wml.Tc;
|
||||
import org.docx4j.wml.Text;
|
||||
import org.docx4j.wml.Tr;
|
||||
|
||||
import javax.xml.bind.JAXBElement;
|
||||
import javax.xml.bind.JAXBException;
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.util.List;
|
||||
|
||||
class Docx4jExample {
|
||||
|
||||
void createDocumentPackage(String outputPath, String imagePath) throws Exception {
|
||||
WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
|
||||
MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
|
||||
mainDocumentPart.addStyledParagraphOfText("Title", "Hello World!");
|
||||
mainDocumentPart.addParagraphOfText("Welcome To Baeldung!");
|
||||
|
||||
ObjectFactory factory = Context.getWmlObjectFactory();
|
||||
P p = factory.createP();
|
||||
R r = factory.createR();
|
||||
Text t = factory.createText();
|
||||
t.setValue("Welcome To Baeldung");
|
||||
r.getContent().add(t);
|
||||
p.getContent().add(r);
|
||||
RPr rpr = factory.createRPr();
|
||||
BooleanDefaultTrue b = new BooleanDefaultTrue();
|
||||
rpr.setB(b);
|
||||
rpr.setI(b);
|
||||
rpr.setCaps(b);
|
||||
Color red = factory.createColor();
|
||||
red.setVal("green");
|
||||
rpr.setColor(red);
|
||||
r.setRPr(rpr);
|
||||
mainDocumentPart.getContent().add(p);
|
||||
|
||||
File image = new File(imagePath);
|
||||
byte[] fileContent = Files.readAllBytes(image.toPath());
|
||||
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordPackage, fileContent);
|
||||
Inline inline = imagePart.createImageInline("Baeldung Image", "Alt Text", 1, 2, false);
|
||||
P Imageparagraph = addImageToParagraph(inline);
|
||||
mainDocumentPart.getContent().add(Imageparagraph);
|
||||
|
||||
int writableWidthTwips = wordPackage.getDocumentModel().getSections().get(0).getPageDimensions().getWritableWidthTwips();
|
||||
int columnNumber = 3;
|
||||
Tbl tbl = TblFactory.createTable(3, 3, writableWidthTwips / columnNumber);
|
||||
List<Object> rows = tbl.getContent();
|
||||
for (Object row : rows) {
|
||||
Tr tr = (Tr) row;
|
||||
List<Object> cells = tr.getContent();
|
||||
for (Object cell : cells) {
|
||||
Tc td = (Tc) cell;
|
||||
td.getContent().add(p);
|
||||
}
|
||||
}
|
||||
|
||||
mainDocumentPart.getContent().add(tbl);
|
||||
File exportFile = new File(outputPath);
|
||||
wordPackage.save(exportFile);
|
||||
}
|
||||
|
||||
boolean isTextExist(String testText) throws Docx4JException, JAXBException {
|
||||
File doc = new File("helloWorld.docx");
|
||||
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(doc);
|
||||
MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();
|
||||
String textNodesXPath = "//w:t";
|
||||
List<Object> paragraphs = mainDocumentPart.getJAXBNodesViaXPath(textNodesXPath, true);
|
||||
for (Object obj : paragraphs) {
|
||||
Text text = (Text) ((JAXBElement) obj).getValue();
|
||||
String textValue = text.getValue();
|
||||
if (textValue != null && textValue.contains(testText)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static P addImageToParagraph(Inline inline) {
|
||||
ObjectFactory factory = new ObjectFactory();
|
||||
P p = factory.createP();
|
||||
R r = factory.createR();
|
||||
p.getContent().add(r);
|
||||
Drawing drawing = factory.createDrawing();
|
||||
r.getContent().add(drawing);
|
||||
drawing.getAnchorOrInline().add(inline);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.baeldung.flink;
|
||||
|
||||
|
||||
import com.baeldung.flink.model.Backup;
|
||||
import com.baeldung.flink.model.InputMessage;
|
||||
import com.baeldung.flink.operator.BackupAggregator;
|
||||
import com.baeldung.flink.operator.InputMessageTimestampAssigner;
|
||||
import com.baeldung.flink.operator.WordsCapitalizer;
|
||||
import org.apache.flink.streaming.api.TimeCharacteristic;
|
||||
import org.apache.flink.streaming.api.datastream.DataStream;
|
||||
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
|
||||
import org.apache.flink.streaming.api.windowing.time.Time;
|
||||
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011;
|
||||
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011;
|
||||
|
||||
import static com.baeldung.flink.connector.Consumers.*;
|
||||
import static com.baeldung.flink.connector.Producers.*;
|
||||
|
||||
public class FlinkDataPipeline {
|
||||
|
||||
public static void capitalize() throws Exception {
|
||||
String inputTopic = "flink_input";
|
||||
String outputTopic = "flink_output";
|
||||
String consumerGroup = "baeldung";
|
||||
String address = "localhost:9092";
|
||||
|
||||
StreamExecutionEnvironment environment =
|
||||
StreamExecutionEnvironment.getExecutionEnvironment();
|
||||
|
||||
FlinkKafkaConsumer011<String> flinkKafkaConsumer =
|
||||
createStringConsumerForTopic(inputTopic, address, consumerGroup);
|
||||
flinkKafkaConsumer.setStartFromEarliest();
|
||||
|
||||
DataStream<String> stringInputStream =
|
||||
environment.addSource(flinkKafkaConsumer);
|
||||
|
||||
FlinkKafkaProducer011<String> flinkKafkaProducer =
|
||||
createStringProducer(outputTopic, address);
|
||||
|
||||
stringInputStream
|
||||
.map(new WordsCapitalizer())
|
||||
.addSink(flinkKafkaProducer);
|
||||
|
||||
environment.execute();
|
||||
}
|
||||
|
||||
public static void createBackup () throws Exception {
|
||||
String inputTopic = "flink_input";
|
||||
String outputTopic = "flink_output";
|
||||
String consumerGroup = "baeldung";
|
||||
String kafkaAddress = "localhost:9092";
|
||||
|
||||
StreamExecutionEnvironment environment =
|
||||
StreamExecutionEnvironment.getExecutionEnvironment();
|
||||
|
||||
environment.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
|
||||
|
||||
FlinkKafkaConsumer011<InputMessage> flinkKafkaConsumer =
|
||||
createInputMessageConsumer(inputTopic, kafkaAddress, consumerGroup);
|
||||
flinkKafkaConsumer.setStartFromEarliest();
|
||||
|
||||
flinkKafkaConsumer
|
||||
.assignTimestampsAndWatermarks(new InputMessageTimestampAssigner());
|
||||
FlinkKafkaProducer011<Backup> flinkKafkaProducer =
|
||||
createBackupProducer(outputTopic, kafkaAddress);
|
||||
|
||||
DataStream<InputMessage> inputMessagesStream =
|
||||
environment.addSource(flinkKafkaConsumer);
|
||||
|
||||
inputMessagesStream
|
||||
.timeWindowAll(Time.hours(24))
|
||||
.aggregate(new BackupAggregator())
|
||||
.addSink(flinkKafkaProducer);
|
||||
|
||||
environment.execute();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
createBackup();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.flink;
|
||||
|
||||
import org.apache.flink.api.common.functions.FlatMapFunction;
|
||||
import org.apache.flink.api.java.tuple.Tuple2;
|
||||
import org.apache.flink.util.Collector;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class LineSplitter implements FlatMapFunction<String, Tuple2<String, Integer>> {
|
||||
|
||||
@Override
|
||||
public void flatMap(String value, Collector<Tuple2<String, Integer>> out) {
|
||||
|
||||
String[] tokens = value.toLowerCase().split("\\W+");
|
||||
Stream.of(tokens).filter(t -> t.length() > 0).forEach(token -> out.collect(new Tuple2<>(token, 1)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.flink;
|
||||
|
||||
import org.apache.flink.api.java.DataSet;
|
||||
import org.apache.flink.api.java.ExecutionEnvironment;
|
||||
import org.apache.flink.api.java.aggregation.Aggregations;
|
||||
import org.apache.flink.api.java.tuple.Tuple2;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class WordCount {
|
||||
|
||||
public static DataSet<Tuple2<String, Integer>> startWordCount(ExecutionEnvironment env, List<String> lines) throws Exception {
|
||||
DataSet<String> text = env.fromCollection(lines);
|
||||
|
||||
return text.flatMap(new LineSplitter()).groupBy(0).aggregate(Aggregations.SUM, 1);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.flink.connector;
|
||||
|
||||
import com.baeldung.flink.model.InputMessage;
|
||||
import com.baeldung.flink.schema.InputMessageDeserializationSchema;
|
||||
import org.apache.flink.api.common.serialization.SimpleStringSchema;
|
||||
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
public class Consumers {
|
||||
|
||||
public static FlinkKafkaConsumer011<String> createStringConsumerForTopic(
|
||||
String topic, String kafkaAddress, String kafkaGroup ) {
|
||||
Properties props = new Properties();
|
||||
props.setProperty("bootstrap.servers", kafkaAddress);
|
||||
props.setProperty("group.id",kafkaGroup);
|
||||
FlinkKafkaConsumer011<String> consumer =
|
||||
new FlinkKafkaConsumer011<>(topic, new SimpleStringSchema(),props);
|
||||
|
||||
return consumer;
|
||||
}
|
||||
|
||||
public static FlinkKafkaConsumer011<InputMessage> createInputMessageConsumer(String topic, String kafkaAddress, String kafkaGroup ) {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("bootstrap.servers", kafkaAddress);
|
||||
properties.setProperty("group.id",kafkaGroup);
|
||||
FlinkKafkaConsumer011<InputMessage> consumer = new FlinkKafkaConsumer011<InputMessage>(
|
||||
topic, new InputMessageDeserializationSchema(),properties);
|
||||
|
||||
return consumer;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.flink.connector;
|
||||
|
||||
import com.baeldung.flink.model.Backup;
|
||||
import com.baeldung.flink.schema.BackupSerializationSchema;
|
||||
import org.apache.flink.api.common.serialization.SimpleStringSchema;
|
||||
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011;
|
||||
|
||||
public class Producers {
|
||||
|
||||
public static FlinkKafkaProducer011<String> createStringProducer(String topic, String kafkaAddress) {
|
||||
return new FlinkKafkaProducer011<>(kafkaAddress, topic, new SimpleStringSchema());
|
||||
}
|
||||
|
||||
public static FlinkKafkaProducer011<Backup> createBackupProducer(String topic, String kafkaAddress) {
|
||||
return new FlinkKafkaProducer011<Backup>(kafkaAddress, topic, new BackupSerializationSchema());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.flink.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public class Backup {
|
||||
|
||||
@JsonProperty("inputMessages")
|
||||
List<InputMessage> inputMessages;
|
||||
@JsonProperty("backupTimestamp")
|
||||
LocalDateTime backupTimestamp;
|
||||
@JsonProperty("uuid")
|
||||
UUID uuid;
|
||||
|
||||
public Backup(List<InputMessage> inputMessages, LocalDateTime backupTimestamp) {
|
||||
this.inputMessages = inputMessages;
|
||||
this.backupTimestamp = backupTimestamp;
|
||||
this.uuid = UUID.randomUUID();
|
||||
}
|
||||
|
||||
public List<InputMessage> getInputMessages() {
|
||||
return inputMessages;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.flink.model;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.google.common.base.Objects;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@JsonSerialize
|
||||
public class InputMessage {
|
||||
String sender;
|
||||
String recipient;
|
||||
LocalDateTime sentAt;
|
||||
String message;
|
||||
|
||||
public InputMessage() {
|
||||
}
|
||||
|
||||
public String getSender() {
|
||||
return sender;
|
||||
}
|
||||
public void setSender(String sender) {
|
||||
this.sender = sender;
|
||||
}
|
||||
|
||||
public String getRecipient() {
|
||||
return recipient;
|
||||
}
|
||||
|
||||
public void setRecipient(String recipient) {
|
||||
this.recipient = recipient;
|
||||
}
|
||||
|
||||
public LocalDateTime getSentAt() {
|
||||
return sentAt;
|
||||
}
|
||||
|
||||
public void setSentAt(LocalDateTime sentAt) {
|
||||
this.sentAt = sentAt;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public InputMessage(String sender, String recipient, LocalDateTime sentAt, String message) {
|
||||
this.sender = sender;
|
||||
this.recipient = recipient;
|
||||
this.sentAt = sentAt;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
InputMessage message1 = (InputMessage) o;
|
||||
return Objects.equal(sender, message1.sender) &&
|
||||
Objects.equal(recipient, message1.recipient) &&
|
||||
Objects.equal(sentAt, message1.sentAt) &&
|
||||
Objects.equal(message, message1.message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(sender, recipient, sentAt, message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.flink.operator;
|
||||
|
||||
import com.baeldung.flink.model.Backup;
|
||||
import com.baeldung.flink.model.InputMessage;
|
||||
import org.apache.flink.api.common.functions.AggregateFunction;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class BackupAggregator implements AggregateFunction<InputMessage, List<InputMessage>, Backup> {
|
||||
@Override
|
||||
public List<InputMessage> createAccumulator() {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<InputMessage> add(InputMessage inputMessage, List<InputMessage> inputMessages) {
|
||||
inputMessages.add(inputMessage);
|
||||
return inputMessages;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Backup getResult(List<InputMessage> inputMessages) {
|
||||
Backup backup = new Backup(inputMessages, LocalDateTime.now());
|
||||
return backup;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<InputMessage> merge(List<InputMessage> inputMessages, List<InputMessage> acc1) {
|
||||
inputMessages.addAll(acc1);
|
||||
return inputMessages;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.flink.operator;
|
||||
|
||||
import com.baeldung.flink.model.InputMessage;
|
||||
import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks;
|
||||
import org.apache.flink.streaming.api.watermark.Watermark;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.time.ZoneId;
|
||||
|
||||
public class InputMessageTimestampAssigner implements AssignerWithPunctuatedWatermarks<InputMessage> {
|
||||
|
||||
@Override
|
||||
public long extractTimestamp(InputMessage element, long previousElementTimestamp) {
|
||||
ZoneId zoneId = ZoneId.systemDefault();
|
||||
return element.getSentAt().atZone(zoneId).toEpochSecond() * 1000;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public Watermark checkAndGetNextWatermark(InputMessage lastElement, long extractedTimestamp) {
|
||||
return new Watermark(extractedTimestamp - 15);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.flink.operator;
|
||||
|
||||
import org.apache.flink.api.common.functions.MapFunction;
|
||||
|
||||
public class WordsCapitalizer implements MapFunction<String, String> {
|
||||
|
||||
@Override
|
||||
public String map(String s) {
|
||||
return s.toUpperCase();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.flink.schema;
|
||||
|
||||
import com.baeldung.flink.model.Backup;
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.apache.flink.api.common.serialization.SerializationSchema;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class BackupSerializationSchema
|
||||
implements SerializationSchema<Backup> {
|
||||
|
||||
static ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
|
||||
Logger logger = LoggerFactory.getLogger(BackupSerializationSchema.class);
|
||||
|
||||
@Override
|
||||
public byte[] serialize(Backup backupMessage) {
|
||||
if(objectMapper == null) {
|
||||
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
|
||||
objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
}
|
||||
try {
|
||||
String json = objectMapper.writeValueAsString(backupMessage);
|
||||
return json.getBytes();
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
logger.error("Failed to parse JSON", e);
|
||||
}
|
||||
return new byte[0];
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.flink.schema;
|
||||
|
||||
import com.baeldung.flink.model.InputMessage;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.apache.flink.api.common.serialization.DeserializationSchema;
|
||||
import org.apache.flink.api.common.typeinfo.TypeInformation;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class InputMessageDeserializationSchema implements
|
||||
DeserializationSchema<InputMessage> {
|
||||
|
||||
static ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
|
||||
|
||||
@Override
|
||||
public InputMessage deserialize(byte[] bytes) throws IOException {
|
||||
|
||||
return objectMapper.readValue(bytes, InputMessage.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEndOfStream(InputMessage inputMessage) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeInformation<InputMessage> getProducedType() {
|
||||
return TypeInformation.of(InputMessage.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.google.sheets;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.api.client.auth.oauth2.Credential;
|
||||
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
|
||||
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
|
||||
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
|
||||
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
|
||||
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
|
||||
import com.google.api.client.json.jackson2.JacksonFactory;
|
||||
import com.google.api.client.util.store.MemoryDataStoreFactory;
|
||||
import com.google.api.services.sheets.v4.SheetsScopes;
|
||||
|
||||
public class GoogleAuthorizeUtil {
|
||||
public static Credential authorize() throws IOException, GeneralSecurityException {
|
||||
InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("/google-sheets-client-secret.json");
|
||||
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
|
||||
|
||||
List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);
|
||||
|
||||
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes).setDataStoreFactory(new MemoryDataStoreFactory())
|
||||
.setAccessType("offline").build();
|
||||
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
|
||||
|
||||
return credential;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.google.sheets;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
import com.google.api.client.auth.oauth2.Credential;
|
||||
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
|
||||
import com.google.api.client.json.jackson2.JacksonFactory;
|
||||
import com.google.api.services.sheets.v4.Sheets;
|
||||
|
||||
public class SheetsServiceUtil {
|
||||
|
||||
private static final String APPLICATION_NAME = "Google Sheets Example";
|
||||
|
||||
public static Sheets getSheetsService() throws IOException, GeneralSecurityException {
|
||||
Credential credential = GoogleAuthorizeUtil.authorize();
|
||||
return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential).setApplicationName(APPLICATION_NAME).build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.infinispan;
|
||||
|
||||
import com.baeldung.infinispan.listener.CacheListener;
|
||||
import org.infinispan.Cache;
|
||||
import org.infinispan.configuration.cache.Configuration;
|
||||
import org.infinispan.configuration.cache.ConfigurationBuilder;
|
||||
import org.infinispan.eviction.EvictionType;
|
||||
import org.infinispan.manager.DefaultCacheManager;
|
||||
import org.infinispan.transaction.LockingMode;
|
||||
import org.infinispan.transaction.TransactionMode;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class CacheConfiguration {
|
||||
|
||||
public static final String SIMPLE_HELLO_WORLD_CACHE = "simple-hello-world-cache";
|
||||
public static final String EXPIRING_HELLO_WORLD_CACHE = "expiring-hello-world-cache";
|
||||
public static final String EVICTING_HELLO_WORLD_CACHE = "evicting-hello-world-cache";
|
||||
public static final String PASSIVATING_HELLO_WORLD_CACHE = "passivating-hello-world-cache";
|
||||
public static final String TRANSACTIONAL_CACHE = "transactional-cache";
|
||||
|
||||
public DefaultCacheManager cacheManager() {
|
||||
return new DefaultCacheManager();
|
||||
}
|
||||
|
||||
public Cache<String, Integer> transactionalCache(DefaultCacheManager cacheManager, CacheListener listener) {
|
||||
return this.buildCache(TRANSACTIONAL_CACHE, cacheManager, listener, transactionalConfiguration());
|
||||
}
|
||||
|
||||
public Cache<String, String> simpleHelloWorldCache(DefaultCacheManager cacheManager, CacheListener listener) {
|
||||
return this.buildCache(SIMPLE_HELLO_WORLD_CACHE, cacheManager, listener, new ConfigurationBuilder().build());
|
||||
}
|
||||
|
||||
public Cache<String, String> expiringHelloWorldCache(DefaultCacheManager cacheManager, CacheListener listener) {
|
||||
return this.buildCache(EXPIRING_HELLO_WORLD_CACHE, cacheManager, listener, expiringConfiguration());
|
||||
}
|
||||
|
||||
public Cache<String, String> evictingHelloWorldCache(DefaultCacheManager cacheManager, CacheListener listener) {
|
||||
return this.buildCache(EVICTING_HELLO_WORLD_CACHE, cacheManager, listener, evictingConfiguration());
|
||||
}
|
||||
|
||||
public Cache<String, String> passivatingHelloWorldCache(DefaultCacheManager cacheManager, CacheListener listener) {
|
||||
return this.buildCache(PASSIVATING_HELLO_WORLD_CACHE, cacheManager, listener, passivatingConfiguration());
|
||||
}
|
||||
|
||||
private <K, V> Cache<K, V> buildCache(String cacheName, DefaultCacheManager cacheManager, CacheListener listener, Configuration configuration) {
|
||||
|
||||
cacheManager.defineConfiguration(cacheName, configuration);
|
||||
Cache<K, V> cache = cacheManager.getCache(cacheName);
|
||||
cache.addListener(listener);
|
||||
return cache;
|
||||
}
|
||||
|
||||
private Configuration expiringConfiguration() {
|
||||
return new ConfigurationBuilder().expiration().lifespan(1, TimeUnit.SECONDS).build();
|
||||
}
|
||||
|
||||
private Configuration evictingConfiguration() {
|
||||
return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).build();
|
||||
}
|
||||
|
||||
private Configuration passivatingConfiguration() {
|
||||
return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).persistence().passivation(true).addSingleFileStore().purgeOnStartup(true).location(System.getProperty("java.io.tmpdir")).build();
|
||||
}
|
||||
|
||||
private Configuration transactionalConfiguration() {
|
||||
return new ConfigurationBuilder().transaction().transactionMode(TransactionMode.TRANSACTIONAL).lockingMode(LockingMode.PESSIMISTIC).build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.infinispan.listener;
|
||||
|
||||
import org.infinispan.notifications.Listener;
|
||||
import org.infinispan.notifications.cachelistener.annotation.*;
|
||||
import org.infinispan.notifications.cachelistener.event.*;
|
||||
|
||||
@Listener
|
||||
public class CacheListener {
|
||||
|
||||
@CacheEntryCreated
|
||||
public void entryCreated(CacheEntryCreatedEvent<String, String> event) {
|
||||
this.printLog("Adding key '" + event.getKey() + "' to cache", event);
|
||||
}
|
||||
|
||||
@CacheEntryExpired
|
||||
public void entryExpired(CacheEntryExpiredEvent<String, String> event) {
|
||||
this.printLog("Expiring key '" + event.getKey() + "' from cache", event);
|
||||
}
|
||||
|
||||
@CacheEntryVisited
|
||||
public void entryVisited(CacheEntryVisitedEvent<String, String> event) {
|
||||
this.printLog("Key '" + event.getKey() + "' was visited", event);
|
||||
}
|
||||
|
||||
@CacheEntryActivated
|
||||
public void entryActivated(CacheEntryActivatedEvent<String, String> event) {
|
||||
this.printLog("Activating key '" + event.getKey() + "' on cache", event);
|
||||
}
|
||||
|
||||
@CacheEntryPassivated
|
||||
public void entryPassivated(CacheEntryPassivatedEvent<String, String> event) {
|
||||
this.printLog("Passivating key '" + event.getKey() + "' from cache", event);
|
||||
}
|
||||
|
||||
@CacheEntryLoaded
|
||||
public void entryLoaded(CacheEntryLoadedEvent<String, String> event) {
|
||||
this.printLog("Loading key '" + event.getKey() + "' to cache", event);
|
||||
}
|
||||
|
||||
@CacheEntriesEvicted
|
||||
public void entriesEvicted(CacheEntriesEvictedEvent<String, String> event) {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
event.getEntries().forEach((key, value) -> builder.append(key).append(", "));
|
||||
System.out.println("Evicting following entries from cache: " + builder.toString());
|
||||
}
|
||||
|
||||
private void printLog(String log, CacheEntryEvent event) {
|
||||
if (!event.isPre()) {
|
||||
System.out.println(log);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.infinispan.repository;
|
||||
|
||||
public class HelloWorldRepository {
|
||||
|
||||
public String getHelloWorld() {
|
||||
try {
|
||||
System.out.println("Executing some heavy query");
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "Hello World!";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.baeldung.infinispan.service;
|
||||
|
||||
import com.baeldung.infinispan.listener.CacheListener;
|
||||
import com.baeldung.infinispan.repository.HelloWorldRepository;
|
||||
import org.infinispan.Cache;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class HelloWorldService {
|
||||
|
||||
private final HelloWorldRepository repository;
|
||||
|
||||
private final Cache<String, String> simpleHelloWorldCache;
|
||||
private final Cache<String, String> expiringHelloWorldCache;
|
||||
private final Cache<String, String> evictingHelloWorldCache;
|
||||
private final Cache<String, String> passivatingHelloWorldCache;
|
||||
|
||||
public HelloWorldService(HelloWorldRepository repository, CacheListener listener, Cache<String, String> simpleHelloWorldCache, Cache<String, String> expiringHelloWorldCache, Cache<String, String> evictingHelloWorldCache,
|
||||
Cache<String, String> passivatingHelloWorldCache) {
|
||||
|
||||
this.repository = repository;
|
||||
|
||||
this.simpleHelloWorldCache = simpleHelloWorldCache;
|
||||
this.expiringHelloWorldCache = expiringHelloWorldCache;
|
||||
this.evictingHelloWorldCache = evictingHelloWorldCache;
|
||||
this.passivatingHelloWorldCache = passivatingHelloWorldCache;
|
||||
}
|
||||
|
||||
public String findSimpleHelloWorld() {
|
||||
String cacheKey = "simple-hello";
|
||||
return simpleHelloWorldCache.computeIfAbsent(cacheKey, k -> repository.getHelloWorld());
|
||||
}
|
||||
|
||||
public String findExpiringHelloWorld() {
|
||||
String cacheKey = "expiring-hello";
|
||||
String helloWorld = simpleHelloWorldCache.get(cacheKey);
|
||||
if (helloWorld == null) {
|
||||
helloWorld = repository.getHelloWorld();
|
||||
simpleHelloWorldCache.put(cacheKey, helloWorld, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
return helloWorld;
|
||||
}
|
||||
|
||||
public String findIdleHelloWorld() {
|
||||
String cacheKey = "idle-hello";
|
||||
String helloWorld = simpleHelloWorldCache.get(cacheKey);
|
||||
if (helloWorld == null) {
|
||||
helloWorld = repository.getHelloWorld();
|
||||
simpleHelloWorldCache.put(cacheKey, helloWorld, -1, TimeUnit.SECONDS, 10, TimeUnit.SECONDS);
|
||||
}
|
||||
return helloWorld;
|
||||
}
|
||||
|
||||
public String findSimpleHelloWorldInExpiringCache() {
|
||||
String cacheKey = "simple-hello";
|
||||
String helloWorld = expiringHelloWorldCache.get(cacheKey);
|
||||
if (helloWorld == null) {
|
||||
helloWorld = repository.getHelloWorld();
|
||||
expiringHelloWorldCache.put(cacheKey, helloWorld);
|
||||
}
|
||||
return helloWorld;
|
||||
}
|
||||
|
||||
public String findEvictingHelloWorld(String key) {
|
||||
String value = evictingHelloWorldCache.get(key);
|
||||
if (value == null) {
|
||||
value = repository.getHelloWorld();
|
||||
evictingHelloWorldCache.put(key, value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public String findPassivatingHelloWorld(String key) {
|
||||
return passivatingHelloWorldCache.computeIfAbsent(key, k -> repository.getHelloWorld());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.infinispan.service;
|
||||
|
||||
import org.infinispan.Cache;
|
||||
import org.springframework.util.StopWatch;
|
||||
|
||||
import javax.transaction.TransactionManager;
|
||||
|
||||
public class TransactionalService {
|
||||
|
||||
private final Cache<String, Integer> transactionalCache;
|
||||
|
||||
private static final String KEY = "key";
|
||||
|
||||
public TransactionalService(Cache<String, Integer> transactionalCache) {
|
||||
this.transactionalCache = transactionalCache;
|
||||
|
||||
transactionalCache.put(KEY, 0);
|
||||
}
|
||||
|
||||
public Integer getQuickHowManyVisits() {
|
||||
try {
|
||||
TransactionManager tm = transactionalCache.getAdvancedCache().getTransactionManager();
|
||||
tm.begin();
|
||||
Integer howManyVisits = transactionalCache.get(KEY);
|
||||
howManyVisits++;
|
||||
System.out.println("Ill try to set HowManyVisits to " + howManyVisits);
|
||||
StopWatch watch = new StopWatch();
|
||||
watch.start();
|
||||
transactionalCache.put(KEY, howManyVisits);
|
||||
watch.stop();
|
||||
System.out.println("I was able to set HowManyVisits to " + howManyVisits + " after waiting " + watch.getTotalTimeSeconds() + " seconds");
|
||||
|
||||
tm.commit();
|
||||
return howManyVisits;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public void startBackgroundBatch() {
|
||||
try {
|
||||
TransactionManager tm = transactionalCache.getAdvancedCache().getTransactionManager();
|
||||
tm.begin();
|
||||
transactionalCache.put(KEY, 1000);
|
||||
System.out.println("HowManyVisits should now be 1000, " + "but we are holding the transaction");
|
||||
Thread.sleep(1000L);
|
||||
tm.rollback();
|
||||
System.out.println("The slow batch suffered a rollback");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.measurement;
|
||||
|
||||
import javax.measure.Quantity;
|
||||
import javax.measure.quantity.Volume;
|
||||
|
||||
public class WaterTank {
|
||||
|
||||
private Quantity<Volume> capacityMeasure;
|
||||
private double capacityDouble;
|
||||
|
||||
public void setCapacityMeasure(Quantity<Volume> capacityMeasure) {
|
||||
this.capacityMeasure = capacityMeasure;
|
||||
}
|
||||
|
||||
public void setCapacityDouble(double capacityDouble) {
|
||||
this.capacityDouble = capacityDouble;
|
||||
}
|
||||
|
||||
public Quantity<Volume> getCapacityMeasure() {
|
||||
return capacityMeasure;
|
||||
}
|
||||
|
||||
public double getCapacityDouble() {
|
||||
return capacityDouble;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.baeldung.opencsv;
|
||||
|
||||
import com.baeldung.opencsv.beans.NamedColumnBean;
|
||||
import com.baeldung.opencsv.beans.SimplePositionBean;
|
||||
import com.baeldung.opencsv.examples.sync.BeanExamples;
|
||||
import com.baeldung.opencsv.examples.sync.CsvReaderExamples;
|
||||
import com.baeldung.opencsv.examples.sync.CsvWriterExamples;
|
||||
import com.baeldung.opencsv.helpers.Helpers;
|
||||
|
||||
import java.io.Reader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class Application {
|
||||
|
||||
/*
|
||||
* Bean Examples.
|
||||
*/
|
||||
|
||||
public static String simpleSyncPositionBeanExample() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Helpers.twoColumnCsvPath();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return BeanExamples.beanBuilderExample(path, SimplePositionBean.class).toString();
|
||||
}
|
||||
|
||||
public static String namedSyncColumnBeanExample() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Helpers.namedColumnCsvPath();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return BeanExamples.beanBuilderExample(path, NamedColumnBean.class).toString();
|
||||
}
|
||||
|
||||
public static String writeSyncCsvFromBeanExample() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Helpers.fileOutBeanPath();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return BeanExamples.writeCsvFromBean(path);
|
||||
}
|
||||
|
||||
/*
|
||||
* CSV Reader Examples.
|
||||
*/
|
||||
|
||||
public static String oneByOneSyncExample() {
|
||||
Reader reader = null;
|
||||
try {
|
||||
reader = Files.newBufferedReader(Helpers.twoColumnCsvPath());
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return CsvReaderExamples.oneByOne(reader).toString();
|
||||
}
|
||||
|
||||
public static String readAllSyncExample() {
|
||||
Reader reader = null;
|
||||
try {
|
||||
reader = Files.newBufferedReader(Helpers.twoColumnCsvPath());
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return CsvReaderExamples.readAll(reader).toString();
|
||||
}
|
||||
|
||||
/*
|
||||
* CSV Writer Examples.
|
||||
*/
|
||||
|
||||
|
||||
public static String csvWriterSyncOneByOne() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Helpers.fileOutOnePath();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return CsvWriterExamples.csvWriterOneByOne(Helpers.fourColumnCsvString(), path);
|
||||
}
|
||||
|
||||
public static String csvWriterSyncAll() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Helpers.fileOutAllPath();
|
||||
} catch (Exception ex) {
|
||||
Helpers.err(ex);
|
||||
}
|
||||
return CsvWriterExamples.csvWriterAll(Helpers.fourColumnCsvString(), path);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
simpleSyncPositionBeanExample();
|
||||
namedSyncColumnBeanExample();
|
||||
writeSyncCsvFromBeanExample();
|
||||
oneByOneSyncExample();
|
||||
readAllSyncExample();
|
||||
csvWriterSyncOneByOne();
|
||||
csvWriterSyncAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.opencsv;
|
||||
|
||||
public class Constants {
|
||||
|
||||
public static final String GENERIC_EXCEPTION = "EXCEPTION ENCOUNTERED: ";
|
||||
public static final String GENERIC_SUCCESS = "SUCCESS";
|
||||
|
||||
public static final String TWO_COLUMN_CSV = "csv/twoColumn.csv";
|
||||
public static final String FOUR_COLUMN_CSV = "csv/fourColumn.csv";
|
||||
public static final String NAMED_COLUMN_CSV = "csv/namedColumn.csv";
|
||||
|
||||
public static final String CSV_All = "csv/writtenAll.csv";
|
||||
public static final String CSV_BEAN = "csv/writtenBean.csv";
|
||||
public static final String CSV_ONE = "csv/writtenOneByOne.csv";
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.opencsv.beans;
|
||||
|
||||
public class CsvBean { }
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.opencsv.beans;
|
||||
|
||||
import com.opencsv.bean.CsvBindByName;
|
||||
|
||||
public class NamedColumnBean extends CsvBean {
|
||||
|
||||
@CsvBindByName(column = "name")
|
||||
private String name;
|
||||
|
||||
//Automatically infer column name as Age
|
||||
@CsvBindByName
|
||||
private int age;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.opencsv.beans;
|
||||
|
||||
import com.opencsv.bean.CsvBindByPosition;
|
||||
|
||||
public class SimplePositionBean extends CsvBean {
|
||||
|
||||
@CsvBindByPosition(position = 0)
|
||||
private String exampleColOne;
|
||||
|
||||
@CsvBindByPosition(position = 1)
|
||||
private String exampleColTwo;
|
||||
|
||||
public String getExampleColOne() {
|
||||
return exampleColOne;
|
||||
}
|
||||
|
||||
private void setExampleColOne(String exampleColOne) {
|
||||
this.exampleColOne = exampleColOne;
|
||||
}
|
||||
|
||||
public String getExampleColTwo() {
|
||||
return exampleColTwo;
|
||||
}
|
||||
|
||||
private void setExampleCsvTwo (String exampleColTwo) {
|
||||
this.exampleColTwo = exampleColTwo;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.opencsv.beans;
|
||||
|
||||
public class WriteExampleBean extends CsvBean {
|
||||
|
||||
private String colA;
|
||||
|
||||
private String colB;
|
||||
|
||||
private String colC;
|
||||
|
||||
public WriteExampleBean(String colA, String colB, String colC) {
|
||||
this.colA = colA;
|
||||
this.colB = colB;
|
||||
this.colC = colC;
|
||||
}
|
||||
|
||||
public String getColA() {
|
||||
return colA;
|
||||
}
|
||||
|
||||
public void setColA(String colA) {
|
||||
this.colA = colA;
|
||||
}
|
||||
|
||||
public String getColB() {
|
||||
return colB;
|
||||
}
|
||||
|
||||
public void setColB(String colB) {
|
||||
this.colB = colB;
|
||||
}
|
||||
|
||||
public String getColC() {
|
||||
return colC;
|
||||
}
|
||||
|
||||
public void setColC(String colC) {
|
||||
this.colC = colC;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user