From 8d202f12589356344e26b7ca15097eec46886055 Mon Sep 17 00:00:00 2001 From: Akira Ajisaka Date: Wed, 29 Jun 2016 07:40:12 -0700 Subject: [PATCH] HADOOP-13235. Use Date and Time API in KafkaSink. --- .../hadoop/metrics2/sink/KafkaSink.java | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/hadoop-tools/hadoop-kafka/src/main/java/org/apache/hadoop/metrics2/sink/KafkaSink.java b/hadoop-tools/hadoop-kafka/src/main/java/org/apache/hadoop/metrics2/sink/KafkaSink.java index d8e5bd8363..ba70ba775d 100644 --- a/hadoop-tools/hadoop-kafka/src/main/java/org/apache/hadoop/metrics2/sink/KafkaSink.java +++ b/hadoop-tools/hadoop-kafka/src/main/java/org/apache/hadoop/metrics2/sink/KafkaSink.java @@ -38,8 +38,10 @@ import java.io.IOException; import java.net.InetAddress; import java.nio.charset.Charset; -import java.text.SimpleDateFormat; -import java.util.Date; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; import java.util.Properties; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -62,6 +64,12 @@ public class KafkaSink implements MetricsSink, Closeable { private String topic = null; private Producer producer = null; + private final DateTimeFormatter dateFormat = + DateTimeFormatter.ofPattern("yyyy-MM-dd"); + private final DateTimeFormatter timeFormat = + DateTimeFormatter.ofPattern("HH:mm:ss"); + private final ZoneId zoneId = ZoneId.systemDefault(); + public void setProducer(Producer p) { this.producer = p; } @@ -121,12 +129,11 @@ public void putMetrics(MetricsRecord record) { // Create the json object. StringBuilder jsonLines = new StringBuilder(); - Long timestamp = record.timestamp(); - Date currDate = new Date(timestamp); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss"); - String date = dateFormat.format(currDate); - String time = timeFormat.format(currDate); + long timestamp = record.timestamp(); + Instant instant = Instant.ofEpochMilli(timestamp); + LocalDateTime ldt = LocalDateTime.ofInstant(instant, zoneId); + String date = ldt.format(dateFormat); + String time = ldt.format(timeFormat); // Collect datapoints and populate the json object. jsonLines.append("{\"hostname\": \"" + hostname);