Merge branch 'master' of https://github.com/eugenp/tutorials into task/BAEL-8844
This commit is contained in:
@@ -5,13 +5,11 @@
|
||||
- [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang)
|
||||
- [Introduction to Javatuples](http://www.baeldung.com/java-tuples)
|
||||
- [Introduction to Javassist](http://www.baeldung.com/javassist)
|
||||
- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded)
|
||||
- [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink)
|
||||
- [Introduction to JSONassert](http://www.baeldung.com/jsonassert)
|
||||
- [Intro to JaVers](http://www.baeldung.com/javers)
|
||||
- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math)
|
||||
- [Intro to Serenity BDD](http://www.baeldung.com/serenity-bdd)
|
||||
- [Introduction to Netty](http://www.baeldung.com/netty)
|
||||
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
|
||||
- [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay)
|
||||
- [Introduction to Quartz](http://www.baeldung.com/quartz)
|
||||
@@ -54,10 +52,7 @@
|
||||
- [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle)
|
||||
- [Guide to google-http-client](http://www.baeldung.com/google-http-client)
|
||||
- [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client)
|
||||
- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup)
|
||||
- [A Docker Guide for Java](http://www.baeldung.com/docker-java-api)
|
||||
- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling)
|
||||
- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic)
|
||||
- [Introduction To OpenCSV](http://www.baeldung.com/opencsv)
|
||||
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
|
||||
- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client)
|
||||
@@ -77,7 +72,6 @@
|
||||
- [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client)
|
||||
- [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools)
|
||||
- [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils)
|
||||
- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel)
|
||||
- [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices)
|
||||
- [Introduction to JavaPoet](http://www.baeldung.com/java-poet)
|
||||
- [Introduction to Joda-Time](http://www.baeldung.com/joda-time)
|
||||
|
||||
+19
-32
@@ -106,21 +106,6 @@
|
||||
<artifactId>javers-core</artifactId>
|
||||
<version>${javers.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-server</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-servlet</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-webapp</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.nats</groupId>
|
||||
@@ -169,6 +154,17 @@
|
||||
<artifactId>commons-dbutils</artifactId>
|
||||
<version>${commons.dbutils.version}</version>
|
||||
</dependency>
|
||||
<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>
|
||||
@@ -193,7 +189,7 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.flink</groupId>
|
||||
<artifactId>flink-test-utils_2.10</artifactId>
|
||||
<artifactId>flink-test-utils_2.11</artifactId>
|
||||
<version>${flink.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
@@ -243,6 +239,11 @@
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- JDO -->
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
@@ -379,11 +380,6 @@
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-all</artifactId>
|
||||
<version>${netty.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
@@ -658,13 +654,7 @@
|
||||
<classifier>test</classifier>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- tomcat -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-catalina</artifactId>
|
||||
<version>${tomcat.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.milyn</groupId>
|
||||
<artifactId>milyn-smooks-all</artifactId>
|
||||
@@ -919,12 +909,11 @@
|
||||
<commons.io.version>2.5</commons.io.version>
|
||||
<commons.dbutils.version>1.6</commons.dbutils.version>
|
||||
<h2.version>1.4.196</h2.version>
|
||||
<jetty.version>9.4.8.v20171121</jetty.version>
|
||||
<jnats.version>1.0</jnats.version>
|
||||
|
||||
<httpclient.version>4.5.3</httpclient.version>
|
||||
<commons.io.version>2.5</commons.io.version>
|
||||
<flink.version>1.2.0</flink.version>
|
||||
<flink.version>1.5.0</flink.version>
|
||||
<jackson.version>2.8.5</jackson.version>
|
||||
<neuroph.version>2.92</neuroph.version>
|
||||
<serenity.version>1.9.26</serenity.version>
|
||||
@@ -932,7 +921,6 @@
|
||||
<serenity.jira.version>1.9.0</serenity.jira.version>
|
||||
<serenity.plugin.version>1.9.27</serenity.plugin.version>
|
||||
<jUnitParams.version>1.1.0</jUnitParams.version>
|
||||
<netty.version>4.1.20.Final</netty.version>
|
||||
<commons.collections.version>4.1</commons.collections.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<java-lsh.version>0.10</java-lsh.version>
|
||||
@@ -961,7 +949,6 @@
|
||||
<kafka.version>1.0.0</kafka.version>
|
||||
<smooks.version>1.7.0</smooks.version>
|
||||
<docker.version>3.0.14</docker.version>
|
||||
<tomcat.version>8.5.24</tomcat.version>
|
||||
<async.http.client.version>2.2.0</async.http.client.version>
|
||||
<infinispan.version>9.1.5.Final</infinispan.version>
|
||||
<opencsv.version>4.1</opencsv.version>
|
||||
|
||||
@@ -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,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,72 @@
|
||||
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];
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.flink.schema;
|
||||
|
||||
import com.baeldung.flink.model.InputMessage;
|
||||
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.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);
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.jetty;
|
||||
|
||||
import javax.servlet.AsyncContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.WriteListener;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
public class AsyncServlet extends HttpServlet {
|
||||
private static final String HEAVY_RESOURCE = "This is some heavy resource that will be served in an async way";
|
||||
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
ByteBuffer content = ByteBuffer.wrap(HEAVY_RESOURCE.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
AsyncContext async = request.startAsync();
|
||||
ServletOutputStream out = response.getOutputStream();
|
||||
out.setWriteListener(new WriteListener() {
|
||||
@Override
|
||||
public void onWritePossible() throws IOException {
|
||||
while (out.isReady()) {
|
||||
if (!content.hasRemaining()) {
|
||||
response.setStatus(200);
|
||||
async.complete();
|
||||
return;
|
||||
}
|
||||
out.write(content.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable t) {
|
||||
getServletContext().log("Async Error", t);
|
||||
async.complete();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.jetty;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
public class BlockingServlet extends HttpServlet {
|
||||
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
response.setContentType("application/json");
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
response.getWriter().println("{ \"status\": \"ok\"}");
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.jetty;
|
||||
|
||||
import org.eclipse.jetty.server.Connector;
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.eclipse.jetty.server.ServerConnector;
|
||||
import org.eclipse.jetty.servlet.ServletHandler;
|
||||
import org.eclipse.jetty.util.thread.QueuedThreadPool;
|
||||
|
||||
class JettyServer {
|
||||
|
||||
private Server server;
|
||||
|
||||
void start() throws Exception {
|
||||
|
||||
int maxThreads = 100;
|
||||
int minThreads = 10;
|
||||
int idleTimeout = 120;
|
||||
|
||||
QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads, minThreads, idleTimeout);
|
||||
|
||||
server = new Server(threadPool);
|
||||
ServerConnector connector = new ServerConnector(server);
|
||||
connector.setPort(8090);
|
||||
server.setConnectors(new Connector[] { connector });
|
||||
|
||||
ServletHandler servletHandler = new ServletHandler();
|
||||
server.setHandler(servletHandler);
|
||||
|
||||
servletHandler.addServletWithMapping(BlockingServlet.class, "/status");
|
||||
servletHandler.addServletWithMapping(AsyncServlet.class, "/heavy/async");
|
||||
|
||||
server.start();
|
||||
|
||||
}
|
||||
|
||||
void stop() throws Exception {
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package com.baeldung.jetty;
|
||||
|
||||
import org.eclipse.jetty.server.Handler;
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.eclipse.jetty.server.ServerConnector;
|
||||
import org.eclipse.jetty.server.handler.HandlerCollection;
|
||||
import org.eclipse.jetty.webapp.WebAppContext;
|
||||
|
||||
/**
|
||||
* Simple factory for creating Jetty basic instances.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class JettyServerFactory {
|
||||
|
||||
/**
|
||||
* Exposed context of the app.
|
||||
*/
|
||||
public final static String APP_PATH = "/myApp";
|
||||
|
||||
/**
|
||||
* The server port.
|
||||
*/
|
||||
public final static int SERVER_PORT = 13133;
|
||||
|
||||
/**
|
||||
* Private constructor to avoid instantiation.
|
||||
*/
|
||||
private JettyServerFactory() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a simple server listening on port 80 with a timeout of 30 seconds
|
||||
* for connections and no handlers.
|
||||
*
|
||||
* @return a server
|
||||
*/
|
||||
public static Server createBaseServer() {
|
||||
Server server = new Server();
|
||||
|
||||
// Adds a connector for port 80 with a timeout of 30 seconds.
|
||||
ServerConnector connector = new ServerConnector(server);
|
||||
connector.setPort(SERVER_PORT);
|
||||
connector.setHost("127.0.0.1");
|
||||
connector.setIdleTimeout(30000);
|
||||
server.addConnector(connector);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a server which delegates the request handling to a web
|
||||
* application.
|
||||
*
|
||||
* @return a server
|
||||
*/
|
||||
public static Server createWebAppServer() {
|
||||
// Adds an handler to a server and returns it.
|
||||
Server server = createBaseServer();
|
||||
String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath();
|
||||
Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH);
|
||||
server.setHandler(webAppHandler);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a server which delegates the request handling to both a logging
|
||||
* handler and to a web application, in this order.
|
||||
*
|
||||
* @return a server
|
||||
*/
|
||||
public static Server createMultiHandlerServer() {
|
||||
Server server = createBaseServer();
|
||||
|
||||
// Creates the handlers and adds them to the server.
|
||||
HandlerCollection handlers = new HandlerCollection();
|
||||
|
||||
String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath();
|
||||
Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH);
|
||||
handlers.addHandler(customRequestHandler);
|
||||
|
||||
Handler loggingRequestHandler = new LoggingRequestHandler();
|
||||
handlers.addHandler(loggingRequestHandler);
|
||||
|
||||
server.setHandler(handlers);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package com.baeldung.jetty;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.eclipse.jetty.server.Handler;
|
||||
import org.eclipse.jetty.server.Request;
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Handler implementation which simply logs that a request has been received.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*/
|
||||
public class LoggingRequestHandler implements Handler {
|
||||
|
||||
/**
|
||||
* Logger.
|
||||
*/
|
||||
private final static Logger LOG = LoggerFactory.getLogger(LoggingRequestHandler.class);
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#addLifeCycleListener(org.
|
||||
* eclipse.jetty.util.component.LifeCycle.Listener)
|
||||
*/
|
||||
@Override
|
||||
public void addLifeCycleListener(Listener arg0) {
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#isFailed()
|
||||
*/
|
||||
@Override
|
||||
public boolean isFailed() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#isRunning()
|
||||
*/
|
||||
@Override
|
||||
public boolean isRunning() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#isStarted()
|
||||
*/
|
||||
@Override
|
||||
public boolean isStarted() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#isStarting()
|
||||
*/
|
||||
@Override
|
||||
public boolean isStarting() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#isStopped()
|
||||
*/
|
||||
@Override
|
||||
public boolean isStopped() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#isStopping()
|
||||
*/
|
||||
@Override
|
||||
public boolean isStopping() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.eclipse.jetty.util.component.LifeCycle#removeLifeCycleListener(org.
|
||||
* eclipse.jetty.util.component.LifeCycle.Listener)
|
||||
*/
|
||||
@Override
|
||||
public void removeLifeCycleListener(Listener arg0) {
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#start()
|
||||
*/
|
||||
@Override
|
||||
public void start() throws Exception {
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#stop()
|
||||
*/
|
||||
@Override
|
||||
public void stop() throws Exception {
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.server.Handler#destroy()
|
||||
*/
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.server.Handler#getServer()
|
||||
*/
|
||||
@Override
|
||||
public Server getServer() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.server.Handler#handle(java.lang.String,
|
||||
* org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest,
|
||||
* javax.servlet.http.HttpServletResponse)
|
||||
*/
|
||||
@Override
|
||||
public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) throws IOException, ServletException {
|
||||
LOG.info("Received a new request");
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server.
|
||||
* Server)
|
||||
*/
|
||||
@Override
|
||||
public void setServer(Server server) {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class ChannelHandlerA extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private Logger logger = Logger.getLogger(getClass().getName());
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
throw new Exception("Ooops");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
|
||||
logger.info("Exception Occurred in ChannelHandler A");
|
||||
ctx.fireExceptionCaught(cause);
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class ChannelHandlerB extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private Logger logger = Logger.getLogger(getClass().getName());
|
||||
|
||||
@Override
|
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
|
||||
logger.info("Exception Handled in ChannelHandler B");
|
||||
logger.info(cause.getLocalizedMessage());
|
||||
// do more exception handling
|
||||
ctx.close();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
|
||||
public class ClientHandler extends ChannelInboundHandlerAdapter {
|
||||
@Override
|
||||
public void channelActive(ChannelHandlerContext ctx) throws Exception {
|
||||
RequestData msg = new RequestData();
|
||||
msg.setIntValue(123);
|
||||
msg.setStringValue("all work and no play makes jack a dull boy");
|
||||
ctx.writeAndFlush(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
System.out.println(msg);
|
||||
ctx.close();
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
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");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
|
||||
public class NettyClient {
|
||||
public static void main(String[] args) throws Exception {
|
||||
String host = "localhost";
|
||||
int port = 8080;
|
||||
EventLoopGroup workerGroup = new NioEventLoopGroup();
|
||||
|
||||
try {
|
||||
Bootstrap b = new Bootstrap();
|
||||
b.group(workerGroup);
|
||||
b.channel(NioSocketChannel.class);
|
||||
b.option(ChannelOption.SO_KEEPALIVE, true);
|
||||
b.handler(new ChannelInitializer<SocketChannel>() {
|
||||
@Override
|
||||
public void initChannel(SocketChannel ch) throws Exception {
|
||||
ch.pipeline().addLast(new RequestDataEncoder(), new ResponseDataDecoder(), new ClientHandler());
|
||||
}
|
||||
});
|
||||
|
||||
ChannelFuture f = b.connect(host, port).sync();
|
||||
|
||||
f.channel().closeFuture().sync();
|
||||
} finally {
|
||||
workerGroup.shutdownGracefully();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
|
||||
public class NettyServer {
|
||||
|
||||
private int port;
|
||||
|
||||
private NettyServer(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
int port;
|
||||
if (args.length > 0) {
|
||||
port = Integer.parseInt(args[0]);
|
||||
} else {
|
||||
port = 8080;
|
||||
}
|
||||
new NettyServer(port).run();
|
||||
}
|
||||
|
||||
private void run() throws Exception {
|
||||
EventLoopGroup bossGroup = new NioEventLoopGroup();
|
||||
EventLoopGroup workerGroup = new NioEventLoopGroup();
|
||||
try {
|
||||
ServerBootstrap b = new ServerBootstrap();
|
||||
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
|
||||
@Override
|
||||
public void initChannel(SocketChannel ch) throws Exception {
|
||||
ch.pipeline().addLast(new RequestDecoder(), new ResponseDataEncoder(), new ProcessingHandler());
|
||||
}
|
||||
}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
|
||||
|
||||
ChannelFuture f = b.bind(port).sync();
|
||||
f.channel().closeFuture().sync();
|
||||
} finally {
|
||||
workerGroup.shutdownGracefully();
|
||||
bossGroup.shutdownGracefully();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
|
||||
public class NettyServerB {
|
||||
|
||||
private int port;
|
||||
|
||||
private NettyServerB(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
private void run() throws Exception {
|
||||
|
||||
EventLoopGroup bossGroup = new NioEventLoopGroup();
|
||||
EventLoopGroup workerGroup = new NioEventLoopGroup();
|
||||
|
||||
try {
|
||||
ServerBootstrap b = new ServerBootstrap();
|
||||
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
|
||||
public void initChannel(SocketChannel ch) throws Exception {
|
||||
ch.pipeline().addLast(new ChannelHandlerA(), new ChannelHandlerB());
|
||||
}
|
||||
}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
|
||||
ChannelFuture f = b.bind(port).sync(); // (7)
|
||||
f.channel().closeFuture().sync();
|
||||
} finally {
|
||||
workerGroup.shutdownGracefully();
|
||||
bossGroup.shutdownGracefully();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
new NettyServerB(8080).run();
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
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 + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
|
||||
public class ProcessingHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
RequestData requestData = (RequestData) msg;
|
||||
ResponseData responseData = new ResponseData();
|
||||
responseData.setIntValue(requestData.getIntValue() * 2);
|
||||
ChannelFuture future = ctx.writeAndFlush(responseData);
|
||||
future.addListener(ChannelFutureListener.CLOSE);
|
||||
System.out.println(requestData);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
public class RequestData {
|
||||
private int intValue;
|
||||
private String stringValue;
|
||||
|
||||
int getIntValue() {
|
||||
return intValue;
|
||||
}
|
||||
|
||||
void setIntValue(int intValue) {
|
||||
this.intValue = intValue;
|
||||
}
|
||||
|
||||
String getStringValue() {
|
||||
return stringValue;
|
||||
}
|
||||
|
||||
void setStringValue(String stringValue) {
|
||||
this.stringValue = stringValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "RequestData{" + "intValue=" + intValue + ", stringValue='" + stringValue + '\'' + '}';
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.handler.codec.MessageToByteEncoder;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
public class RequestDataEncoder extends MessageToByteEncoder<RequestData> {
|
||||
|
||||
private final Charset charset = Charset.forName("UTF-8");
|
||||
|
||||
@Override
|
||||
protected void encode(ChannelHandlerContext ctx, RequestData msg, ByteBuf out) throws Exception {
|
||||
out.writeInt(msg.getIntValue());
|
||||
out.writeInt(msg.getStringValue().length());
|
||||
out.writeCharSequence(msg.getStringValue(), charset);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.List;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.handler.codec.ReplayingDecoder;
|
||||
|
||||
public class RequestDecoder extends ReplayingDecoder<RequestData> {
|
||||
|
||||
private final Charset charset = Charset.forName("UTF-8");
|
||||
|
||||
@Override
|
||||
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
|
||||
RequestData data = new RequestData();
|
||||
data.setIntValue(in.readInt());
|
||||
int strLen = in.readInt();
|
||||
data.setStringValue(in.readCharSequence(strLen, charset).toString());
|
||||
out.add(data);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user