Merge branch 'master' into BAEL-1423-jctools

This commit is contained in:
Tom Hombergs
2018-04-16 22:06:44 +02:00
committed by GitHub
413 changed files with 311233 additions and 971 deletions
@@ -1,31 +1,35 @@
package com.baeldung.jnats;
import io.nats.client.*;
import java.io.IOException;
import java.util.*;
import io.nats.client.AsyncSubscription;
import io.nats.client.Connection;
import io.nats.client.Message;
import io.nats.client.Nats;
import io.nats.client.Options;
import io.nats.client.Subscription;
import io.nats.client.SyncSubscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NatsClient {
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
private String serverURI;
public final class NatsClient {
private Connection natsConnection;
private final String serverURI;
private Map<String, Subscription> subscriptions = new HashMap<>();
private final Connection natsConnection;
private final Map<String, Subscription> subscriptions = new HashMap<>();
private final static Logger log = LoggerFactory.getLogger(NatsClient.class);
public NatsClient() {
NatsClient() {
this.serverURI = "jnats://localhost:4222";
natsConnection = initConnection(serverURI);
}
public NatsClient(String serverURI) {
if ((serverURI != null) && (!serverURI.isEmpty())) {
this.serverURI = serverURI;
} else {
@@ -40,59 +44,33 @@ public class NatsClient {
natsConnection.close();
}
private Connection initConnection(String uri) {
try {
Options options = new Options.Builder()
.errorCb(new ExceptionHandler() {
@Override
public void onException(NATSException ex) {
log.error("Connection Exception: ", ex);
}
})
.disconnectedCb(new DisconnectedCallback() {
@Override
public void onDisconnect(ConnectionEvent event) {
log.error("Channel disconnected: {}", event.getConnection());
}
})
.reconnectedCb(new ReconnectedCallback() {
@Override
public void onReconnect(ConnectionEvent event) {
log.error("Reconnected to server: {}", event.getConnection());
}
})
.errorCb(ex -> log.error("Connection Exception: ", ex))
.disconnectedCb(event -> log.error("Channel disconnected: {}", event.getConnection()))
.reconnectedCb(event -> log.error("Reconnected to server: {}", event.getConnection()))
.build();
return Nats.connect(uri, options);
} catch (IOException ioe) {
log.error("Error connecting to NATs! ", ioe);
return null;
}
}
public void publishMessage(String topic, String replyTo, String message) {
void publishMessage(String topic, String replyTo, String message) {
try {
// Simple Publisher
natsConnection.publish(topic, replyTo, message.getBytes());
} catch (IOException ioe) {
log.error("Error publishing message: {} to {} ", message, topic, ioe);
}
}
public void subscribeAsync(String topic) {
// Simple Async Subscriber
AsyncSubscription subscription = natsConnection.subscribe(topic, new MessageHandler() {
@Override
public void onMessage(Message msg) {
log.info("Received message on {}", msg.getSubject());
}
});
AsyncSubscription subscription = natsConnection.subscribe(
topic, msg -> log.info("Received message on {}", msg.getSubject()));
if (subscription == null) {
log.error("Error subscribing to {}", topic);
@@ -101,13 +79,11 @@ public class NatsClient {
}
}
public SyncSubscription subscribeSync(String topic) {
// Simple Sync Subscriber
SyncSubscription subscribeSync(String topic) {
return natsConnection.subscribe(topic);
}
public void unsubscribe(String topic) {
try {
Subscription subscription = subscriptions.get(topic);
@@ -116,15 +92,12 @@ public class NatsClient {
} else {
log.error("{} not found. Unable to unsubscribe.", topic);
}
} catch (IOException ioe) {
log.error("Error unsubscribing from {} ", topic, ioe);
}
}
public Message makeRequest(String topic, String request) {
Message makeRequest(String topic, String request) {
try {
return natsConnection.request(topic, request.getBytes(), 100);
} catch (IOException | InterruptedException ioe) {
@@ -133,7 +106,7 @@ public class NatsClient {
}
}
public void installReply(String topic, String reply) {
void installReply(String topic, String reply) {
natsConnection.subscribe(topic, message -> {
try {
natsConnection.publish(message.getReplyTo(), reply.getBytes());
@@ -143,8 +116,7 @@ public class NatsClient {
});
}
public SyncSubscription joinQueueGroup(String topic, String queue) {
SyncSubscription joinQueueGroup(String topic, String queue) {
return natsConnection.subscribe(topic, queue);
}
}
@@ -0,0 +1,49 @@
package com.baeldung.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
public class CalculatorOperationHandler extends SimpleChannelInboundHandler<Operation> {
protected void channelRead0(ChannelHandlerContext ctx, Operation msg) throws Exception {
Long result = calculateEndpoint(msg);
sendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CREATED), result.toString());
ctx.fireChannelRead(result);
}
private long calculateEndpoint(Operation operation) {
String operator = operation.getOperator().toLowerCase().trim();
switch (operator) {
case "add":
return operation.getNumber1() + operation.getNumber2();
case "multiply":
return operation.getNumber1() * operation.getNumber2();
default:
throw new IllegalArgumentException("Operation not defined");
}
}
public static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpResponse res, String content) {
// Generate an error page if response getStatus code is not OK (200).
ByteBuf buf = Unpooled.copiedBuffer(content, CharsetUtil.UTF_8);
res.content().writeBytes(buf);
HttpUtil.setContentLength(res, res.content().readableBytes());
ctx.channel().writeAndFlush(res);
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
sendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR), "Operation not defined");
ctx.fireExceptionCaught(cause);
}
}
@@ -0,0 +1,40 @@
package com.baeldung.netty;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
public class HttpMessageHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
String uri = msg.uri();
HttpMethod httpMethod = msg.method();
HttpHeaders headers = msg.headers();
if (HttpMethod.GET == httpMethod) {
String[] uriComponents = uri.split("[?]");
String endpoint = uriComponents[0];
String[] queryParams = uriComponents[1].split("&");
if ("/calculate".equalsIgnoreCase(endpoint)) {
String[] firstQueryParam = queryParams[0].split("=");
String[] secondQueryParam = queryParams[1].split("=");
Integer a = Integer.valueOf(firstQueryParam[1]);
Integer b = Integer.valueOf(secondQueryParam[1]);
String operator = headers.get("operator");
Operation operation = new Operation(a, b, operator);
ctx.fireChannelRead(operation);
}
} else {
throw new UnsupportedOperationException("HTTP method not supported");
}
}
}
@@ -0,0 +1,49 @@
package com.baeldung.netty;
import java.io.Serializable;
public class Operation implements Serializable {
private Integer number1;
private Integer number2;
private String operator;
public Operation(Integer number1, Integer number2, String operator) {
this.number1 = number1;
this.number2 = number2;
this.operator = operator;
}
public Integer getNumber1() {
return number1;
}
public void setNumber1(Integer number1) {
this.number1 = number1;
}
public Integer getNumber2() {
return number2;
}
public void setNumber2(Integer number2) {
this.number2 = number2;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
@Override
public String toString() {
return "Operation{" +
"number1=" + number1 +
", number2=" + number2 +
", operator='" + operator + '\'' +
'}';
}
}
@@ -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;
}
}
@@ -0,0 +1,61 @@
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) {
CsvTransfer csvTransfer = new CsvTransfer();
try {
ColumnPositionMappingStrategy ms = new ColumnPositionMappingStrategy();
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);
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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>();
}
}
@@ -0,0 +1,5 @@
ColA,ColB,ColC,ColD
A,B,B,B
C,D,W,W
G,G,E,E
G,F,Q,Q
1 ColA ColB ColC ColD
2 A B B B
3 C D W W
4 G G E E
5 G F Q Q
@@ -0,0 +1,5 @@
name,age
adam,1000
martin,27
gigi,41
seraphine,30
1 name age
2 adam 1000
3 martin 27
4 gigi 41
5 seraphine 30
@@ -0,0 +1,5 @@
ColA,ColB
A,B
C,D
G,G
G,F
1 ColA ColB
2 A B
3 C D
4 G G
5 G F