[BAEL-16003] renamed artifactId. Removed specified articles from libraries module. Added smooks + google sheets resources into libraries-data-2. Tidied up libraries pom, removing unused dependencies.

This commit is contained in:
Sjmillington
2019-08-05 16:50:34 +01:00
parent 0f06cd46ca
commit 4dbeacad35
100 changed files with 2 additions and 2534 deletions

View File

@@ -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;
}
}

View File

@@ -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();
}
}

View File

@@ -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)));
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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());
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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();
}
}

View File

@@ -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];
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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);
}
}
}

View File

@@ -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!";
}
}

View File

@@ -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());
}
}

View File

@@ -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();
}
}
}

View File

@@ -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;
}
}

View File

@@ -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();
}
}

View File

@@ -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";
}

View File

@@ -0,0 +1,3 @@
package com.baeldung.opencsv.beans;
public class CsvBean { }

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,63 @@
package com.baeldung.opencsv.examples.sync;
import com.baeldung.opencsv.beans.CsvBean;
import com.baeldung.opencsv.beans.WriteExampleBean;
import com.baeldung.opencsv.helpers.Helpers;
import com.baeldung.opencsv.pojos.CsvTransfer;
import com.opencsv.CSVWriter;
import com.opencsv.bean.*;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class BeanExamples {
public static List<CsvBean> beanBuilderExample(Path path, Class clazz) {
ColumnPositionMappingStrategy ms = new ColumnPositionMappingStrategy();
return beanBuilderExample(path, clazz, ms);
}
public static List<CsvBean> beanBuilderExample(Path path, Class clazz, MappingStrategy ms) {
CsvTransfer csvTransfer = new CsvTransfer();
try {
ms.setType(clazz);
Reader reader = Files.newBufferedReader(path);
CsvToBean cb = new CsvToBeanBuilder(reader).withType(clazz)
.withMappingStrategy(ms)
.build();
csvTransfer.setCsvList(cb.parse());
reader.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return csvTransfer.getCsvList();
}
public static String writeCsvFromBean(Path path) {
try {
Writer writer = new FileWriter(path.toString());
StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer).withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.build();
List<CsvBean> list = new ArrayList<>();
list.add(new WriteExampleBean("Test1", "sfdsf", "fdfd"));
list.add(new WriteExampleBean("Test2", "ipso", "facto"));
sbc.write(list);
writer.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return Helpers.readFile(path);
}
}

View File

@@ -0,0 +1,63 @@
package com.baeldung.opencsv.examples.sync;
import com.baeldung.opencsv.helpers.Helpers;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
public class CsvReaderExamples {
public static List<String[]> readAll(Reader reader) {
CSVParser parser = new CSVParserBuilder()
.withSeparator(',')
.withIgnoreQuotations(true)
.build();
CSVReader csvReader = new CSVReaderBuilder(reader)
.withSkipLines(0)
.withCSVParser(parser)
.build();
List<String[]> list = new ArrayList<>();
try {
list = csvReader.readAll();
reader.close();
csvReader.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return list;
}
public static List<String[]> oneByOne(Reader reader) {
List<String[]> list = new ArrayList<>();
try {
CSVParser parser = new CSVParserBuilder()
.withSeparator(',')
.withIgnoreQuotations(true)
.build();
CSVReader csvReader = new CSVReaderBuilder(reader)
.withSkipLines(0)
.withCSVParser(parser)
.build();
String[] line;
while ((line = csvReader.readNext()) != null) {
list.add(line);
}
reader.close();
csvReader.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return list;
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.opencsv.examples.sync;
import com.baeldung.opencsv.helpers.Helpers;
import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.nio.file.Path;
import java.util.List;
public class CsvWriterExamples {
public static String csvWriterOneByOne(List<String[]> stringArray, Path path) {
try {
CSVWriter writer = new CSVWriter(new FileWriter(path.toString()));
for (String[] array : stringArray) {
writer.writeNext(array);
}
writer.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return Helpers.readFile(path);
}
public static String csvWriterAll(List<String[]> stringArray, Path path) {
try {
CSVWriter writer = new CSVWriter(new FileWriter(path.toString()));
writer.writeAll(stringArray);
writer.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return Helpers.readFile(path);
}
}

View File

@@ -0,0 +1,108 @@
package com.baeldung.opencsv.helpers;
import com.baeldung.opencsv.Constants;
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class Helpers {
/**
* Write Files
*/
public static Path fileOutAllPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.CSV_All).toURI();
return Paths.get(uri);
}
public static Path fileOutBeanPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.CSV_BEAN).toURI();
return Paths.get(uri);
}
public static Path fileOutOnePath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.CSV_ONE).toURI();
return Paths.get(uri);
}
/**
* Read Files
*/
public static Path twoColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.TWO_COLUMN_CSV).toURI();
return Paths.get(uri);
}
public static Path fourColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.FOUR_COLUMN_CSV).toURI();
return Paths.get(uri);
}
public static Path namedColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.NAMED_COLUMN_CSV).toURI();
return Paths.get(uri);
}
/**
* Simple File Reader
*/
public static String readFile(Path path) {
String response = "";
try {
FileReader fr = new FileReader(path.toString());
BufferedReader br = new BufferedReader(fr);
String strLine;
StringBuffer sb = new StringBuffer();
while ((strLine = br.readLine()) != null) {
sb.append(strLine);
}
response = sb.toString();
System.out.println(response);
fr.close();
br.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return response;
}
/**
* Dummy Data for Writing.
*/
public static List<String[]> twoColumnCsvString() {
List<String[]> list = new ArrayList<>();
list.add(new String[]{"ColA", "ColB"});
list.add(new String[]{"A", "B"});
return list;
}
public static List<String[]> fourColumnCsvString() {
List<String[]> list = new ArrayList<>();
list.add(new String[]{"ColA", "ColB", "ColC", "ColD"});
list.add(new String[]{"A", "B", "A", "B"});
list.add(new String[]{"BB", "AB", "AA", "B"});
return list;
}
/**
* Message Helpers
*/
public static void print(String msg) {
System.out.println(msg);
}
public static void err(Exception ex) {
System.out.println(Constants.GENERIC_EXCEPTION + " " + ex);
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.opencsv.pojos;
import com.baeldung.opencsv.beans.CsvBean;
import java.util.ArrayList;
import java.util.List;
public class CsvTransfer {
private List<String[]> csvStringList;
private List<CsvBean> csvList;
public CsvTransfer() {}
public List<String[]> getCsvStringList() {
if (csvStringList != null) return csvStringList;
return new ArrayList<String[]>();
}
public void addLine(String[] line) {
if (this.csvList == null) this.csvStringList = new ArrayList<>();
this.csvStringList.add(line);
}
public void setCsvStringList(List<String[]> csvStringList) {
this.csvStringList = csvStringList;
}
public void setCsvList(List<CsvBean> csvList) {
this.csvList = csvList;
}
public List<CsvBean> getCsvList() {
if (csvList != null) return csvList;
return new ArrayList<CsvBean>();
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.smooks.converter;
import com.baeldung.smooks.model.Order;
import org.milyn.Smooks;
import org.milyn.payload.JavaResult;
import org.milyn.payload.StringResult;
import org.xml.sax.SAXException;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
public class OrderConverter {
public Order convertOrderXMLToOrderObject(String path) throws IOException, SAXException {
Smooks smooks = new Smooks(OrderConverter.class.getResourceAsStream("/smooks/smooks-mapping.xml"));
try {
JavaResult javaResult = new JavaResult();
smooks.filterSource(new StreamSource(OrderConverter.class.getResourceAsStream(path)), javaResult);
return (Order) javaResult.getBean("order");
} finally {
smooks.close();
}
}
public String convertOrderXMLtoEDIFACT(String path) throws IOException, SAXException {
return convertDocumentWithTempalte(path, "/smooks/smooks-transform-edi.xml");
}
public String convertOrderXMLtoEmailMessage(String path) throws IOException, SAXException {
return convertDocumentWithTempalte(path, "/smooks/smooks-transform-email.xml");
}
private String convertDocumentWithTempalte(String path, String config) throws IOException, SAXException {
Smooks smooks = new Smooks(config);
try {
StringResult stringResult = new StringResult();
smooks.filterSource(new StreamSource(OrderConverter.class.getResourceAsStream(path)), stringResult);
return stringResult.toString();
} finally {
smooks.close();
}
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.smooks.converter;
import org.milyn.Smooks;
import org.milyn.payload.JavaResult;
import org.milyn.payload.StringResult;
import org.milyn.validation.ValidationResult;
import org.xml.sax.SAXException;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
public class OrderValidator {
public ValidationResult validate(String path) throws IOException, SAXException {
Smooks smooks = new Smooks(OrderValidator.class.getResourceAsStream("/smooks/smooks-validation.xml"));
try {
StringResult xmlResult = new StringResult();
JavaResult javaResult = new JavaResult();
ValidationResult validationResult = new ValidationResult();
smooks.filterSource(new StreamSource(OrderValidator.class.getResourceAsStream(path)), xmlResult, javaResult, validationResult);
return validationResult;
} finally {
smooks.close();
}
}
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.smooks.model;
public class Item {
public Item() {
}
public Item(String code, Double price, Integer quantity) {
this.code = code;
this.price = price;
this.quantity = quantity;
}
private String code;
private Double price;
private Integer quantity;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Item item = (Item) o;
if (code != null ? !code.equals(item.code) : item.code != null)
return false;
if (price != null ? !price.equals(item.price) : item.price != null)
return false;
return quantity != null ? quantity.equals(item.quantity) : item.quantity == null;
}
@Override
public int hashCode() {
int result = code != null ? code.hashCode() : 0;
result = 31 * result + (price != null ? price.hashCode() : 0);
result = 31 * result + (quantity != null ? quantity.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Item{" + "code='" + code + '\'' + ", price=" + price + ", quantity=" + quantity + '}';
}
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.smooks.model;
import java.util.Date;
import java.util.List;
public class Order {
private Date creationDate;
private Long number;
private Status status;
private Supplier supplier;
private List<Item> items;
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Long getNumber() {
return number;
}
public void setNumber(Long number) {
this.number = number;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Supplier getSupplier() {
return supplier;
}
public void setSupplier(Supplier supplier) {
this.supplier = supplier;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.smooks.model;
public enum Status {
NEW, IN_PROGRESS, FINISHED
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.smooks.model;
public class Supplier {
private String name;
private String phoneNumber;
public Supplier() {
}
public Supplier(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Supplier supplier = (Supplier) o;
if (name != null ? !name.equals(supplier.name) : supplier.name != null)
return false;
return phoneNumber != null ? phoneNumber.equals(supplier.phoneNumber) : supplier.phoneNumber == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0);
return result;
}
}