You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@rocketmq.apache.org by zh...@apache.org on 2022/06/28 06:21:33 UTC
[rocketmq-connect] branch master updated: [ISSUE #155] Optimize the record converter parser (#158)
This is an automated email from the ASF dual-hosted git repository.
zhoubo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-connect.git
The following commit(s) were added to refs/heads/master by this push:
new a7bad20 [ISSUE #155] Optimize the record converter parser (#158)
a7bad20 is described below
commit a7bad20feec0b33fad041a8e16a186549f78febb
Author: xiaoyi <su...@163.com>
AuthorDate: Tue Jun 28 14:21:28 2022 +0800
[ISSUE #155] Optimize the record converter parser (#158)
* upgrade rocketmq connect JDBC plug-in #153
* init converter
* Optimize the record converter parser #155
* fixed
* test json converter #155
* support v0.1.3 api
* upgrade rocketmq jdbc plugin and runtime api to 0.1.3 #153
* fixed
* fixed
* test json converter #155
* add Decimal logical
* add converter test
* optimize transform api
* upgrade api to 0.1.3
* fixed
* fixed
* fixed
* fixed
* fixed
* upgrade converter api
* fixed
* add retry converter
* fixed
* fixed
* fixed
Co-authored-by: “sunxiaojian” <“sunxiaojian926@163.com”>
Co-authored-by: xiaojian.sxj <xi...@alibaba-inc.com>
---
connectors/rocketmq-connect-jdbc/pom.xml | 1 +
.../connect/jdbc/connector/JdbcSinkTask.java | 2 +-
.../jdbc/dialect/PreparedStatementBinder.java | 1 -
.../cache/Cache.java} | 47 +-
.../connect/runtime/common/cache/LRUCache.java | 82 ++
.../runtime/connectorwrapper/TransformChain.java | 9 +-
.../connect/runtime/connectorwrapper/Worker.java | 14 +-
.../runtime/connectorwrapper/WorkerDirectTask.java | 19 +-
.../runtime/connectorwrapper/WorkerSinkTask.java | 49 +-
.../runtime/connectorwrapper/WorkerSourceTask.java | 73 +-
.../runtime/converter/ByteBufferConverter.java | 2 +-
.../connect/runtime/converter/ByteConverter.java | 2 +-
.../runtime/converter/ByteMapConverter.java | 2 +-
.../converter/record/ByteArrayConverter.java | 60 ++
.../runtime/converter/record/DoubleConverter.java | 33 +
.../runtime/converter/record/FloatConverter.java | 31 +
.../runtime/converter/record/IntegerConverter.java | 31 +
.../runtime/converter/record/LongConverter.java | 32 +
.../runtime/converter/record/NumberConverter.java | 87 ++
.../runtime/converter/record/ShortConverter.java | 32 +
.../runtime/converter/record/StringConverter.java | 78 ++
.../converter/record/json/DecimalFormat.java | 36 +
.../converter/record/json/JsonConverter.java | 800 +++++++++++++++++++
.../converter/record/json/JsonConverterConfig.java | 94 +++
.../runtime/converter/record/json/JsonSchema.java | 128 +++
.../runtime/errors/ReporterManagerUtil.java | 4 +-
.../runtime/errors/WorkerErrorRecordReporter.java | 31 +-
.../serialization/ByteArrayDeserializer.java | 25 +
.../runtime/serialization/ByteArraySerializer.java | 24 +
.../serialization/ByteBufferDeserializer.java | 30 +
.../serialization/ByteBufferSerializer.java | 41 +
.../runtime/serialization/Deserializer.java | 63 ++
.../runtime/serialization/DoubleDeserializer.java | 38 +
.../runtime/serialization/DoubleSerializer.java | 38 +
.../runtime/serialization/FloatDeserializer.java | 38 +
.../runtime/serialization/FloatSerializer.java | 34 +
.../runtime/serialization/IntegerDeserializer.java | 38 +
.../runtime/serialization/IntegerSerializer.java | 33 +
.../runtime/serialization/JsonDeserializer.java | 43 +
.../runtime/serialization/JsonSerializer.java | 50 ++
.../runtime/serialization/LongDeserializer.java | 38 +
.../runtime/serialization/LongSerializer.java | 37 +
.../connect/runtime/serialization/Serializer.java | 61 ++
.../runtime/serialization/ShortDeserializer.java | 39 +
.../runtime/serialization/ShortSerializer.java | 31 +
.../runtime/serialization/StringDeserializer.java | 49 ++
.../runtime/serialization/StringSerializer.java | 51 ++
.../connect/runtime/common/FastJsonTest.java | 30 +
.../runtime/connectorwrapper/WorkerTest.java | 3 +-
.../runtime/converter/JsonConverterTest.java | 43 -
.../record/AbstractRecordConverterTest.java | 12 +
.../converter/record/DoubleConverterTest.java | 25 +
.../converter/record/IntegerConverterTest.java | 27 +
.../converter/record/JsonConverterConfigTest.java | 38 +
.../converter/record/JsonConverterTest.java | 881 +++++++++++++++++++++
.../converter/record/LongConverterTest.java | 25 +
.../converter/record/ShortConverterTest.java | 25 +
.../converter/record/StringConverterTest.java | 25 +
.../connect/runtime/rest/RestHandlerTest.java | 4 +-
.../runtime/store/FileBaseKeyValueStoreTest.java | 1 +
60 files changed, 3577 insertions(+), 143 deletions(-)
diff --git a/connectors/rocketmq-connect-jdbc/pom.xml b/connectors/rocketmq-connect-jdbc/pom.xml
index f525cd7..4113d1a 100644
--- a/connectors/rocketmq-connect-jdbc/pom.xml
+++ b/connectors/rocketmq-connect-jdbc/pom.xml
@@ -46,6 +46,7 @@
<junit.version>4.13.1</junit.version>
<assertj.version>2.6.0</assertj.version>
<mockito.version>2.6.3</mockito.version>
+ <!--rocket connect api-->
<openmessaging-connector.version>0.1.3</openmessaging-connector.version>
<openmessaging-api.version>0.3.1-alpha</openmessaging-api.version>
diff --git a/connectors/rocketmq-connect-jdbc/src/main/java/org/apache/rocketmq/connect/jdbc/connector/JdbcSinkTask.java b/connectors/rocketmq-connect-jdbc/src/main/java/org/apache/rocketmq/connect/jdbc/connector/JdbcSinkTask.java
index e967849..e604791 100644
--- a/connectors/rocketmq-connect-jdbc/src/main/java/org/apache/rocketmq/connect/jdbc/connector/JdbcSinkTask.java
+++ b/connectors/rocketmq-connect-jdbc/src/main/java/org/apache/rocketmq/connect/jdbc/connector/JdbcSinkTask.java
@@ -89,7 +89,7 @@ public class JdbcSinkTask extends SinkTask {
sqlAllMessagesException.setNextException(sqle);
return sqlAllMessagesException;
}
-
+
/**
* Start the component
*
diff --git a/connectors/rocketmq-connect-jdbc/src/main/java/org/apache/rocketmq/connect/jdbc/dialect/PreparedStatementBinder.java b/connectors/rocketmq-connect-jdbc/src/main/java/org/apache/rocketmq/connect/jdbc/dialect/PreparedStatementBinder.java
index 75155c4..ddd5532 100644
--- a/connectors/rocketmq-connect-jdbc/src/main/java/org/apache/rocketmq/connect/jdbc/dialect/PreparedStatementBinder.java
+++ b/connectors/rocketmq-connect-jdbc/src/main/java/org/apache/rocketmq/connect/jdbc/dialect/PreparedStatementBinder.java
@@ -17,7 +17,6 @@
package org.apache.rocketmq.connect.jdbc.dialect;
import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.openmessaging.connector.api.data.ConnectRecord;
import io.openmessaging.connector.api.data.Field;
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteBufferConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/common/cache/Cache.java
similarity index 63%
copy from rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteBufferConverter.java
copy to rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/common/cache/Cache.java
index ce3f315..ebf9052 100644
--- a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteBufferConverter.java
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/common/cache/Cache.java
@@ -15,22 +15,43 @@
* limitations under the License.
*/
-package org.apache.rocketmq.connect.runtime.converter;
-
-import io.openmessaging.connector.api.data.Converter;
-import java.nio.ByteBuffer;
+package org.apache.rocketmq.connect.runtime.common.cache;
/**
- * ByteBuffer converter.
+ * cache
+ *
+ * @param <K>
+ * @param <V>
*/
-public class ByteBufferConverter implements Converter<ByteBuffer> {
+public interface Cache<K, V> {
+
+ /**
+ * @param key
+ * @return
+ */
+ V get(K key);
+
+ /**
+ * put a data to cache
+ *
+ * @param key
+ * @param value
+ */
+ void put(K key, V value);
+
+
+ /**
+ * remove a data to cache
+ *
+ * @param key
+ * @return
+ */
+ boolean remove(K key);
+
- @Override
- public byte[] objectToByte(ByteBuffer object) {
- return object.array();
- }
+ /**
+ * @return
+ */
+ long size();
- @Override public ByteBuffer byteToObject(byte[] bytes) {
- return ByteBuffer.wrap(bytes);
- }
}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/common/cache/LRUCache.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/common/cache/LRUCache.java
new file mode 100644
index 0000000..4848acb
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/common/cache/LRUCache.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.rocketmq.connect.runtime.common.cache;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * lru cache
+ *
+ * @param <K>
+ * @param <V>
+ */
+public class LRUCache<K, V> implements Cache<K, V> {
+
+ private final Map<K, V> cache;
+
+ public LRUCache(final int maxSize) {
+ cache = Collections.synchronizedMap(new LinkedHashMap<K, V>(300, 1.1F, true) {
+ @Override
+ protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
+ return this.size() > maxSize;
+ }
+ });
+ }
+
+ /**
+ * @param key
+ * @return
+ */
+ @Override
+ public V get(K key) {
+ return cache.get(key);
+ }
+
+ /**
+ * put a data to cache
+ *
+ * @param key
+ * @param value
+ */
+ @Override
+ public void put(K key, V value) {
+ cache.put(key, value);
+ }
+
+ /**
+ * remove a data to cache
+ *
+ * @param key
+ * @return
+ */
+ @Override
+ public boolean remove(K key) {
+ return cache.remove(key) != null;
+ }
+
+ /**
+ * cache size
+ * @return
+ */
+ @Override
+ public long size() {
+ return cache.size();
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/TransformChain.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/TransformChain.java
index 35e162a..df09f36 100644
--- a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/TransformChain.java
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/TransformChain.java
@@ -23,11 +23,6 @@ import io.openmessaging.KeyValue;
import io.openmessaging.connector.api.component.Transform;
import io.openmessaging.connector.api.data.ConnectRecord;
import io.openmessaging.internal.DefaultKeyValue;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.connect.runtime.common.LoggerName;
@@ -39,6 +34,10 @@ import org.apache.rocketmq.connect.runtime.utils.PluginClassLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
public class TransformChain<R extends ConnectRecord> implements AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(LoggerName.ROCKETMQ_RUNTIME);
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/Worker.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/Worker.java
index c1bedaf..319332a 100644
--- a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/Worker.java
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/Worker.java
@@ -25,7 +25,7 @@ import io.openmessaging.connector.api.component.task.Task;
import io.openmessaging.connector.api.component.task.sink.SinkTask;
import io.openmessaging.connector.api.component.task.source.SourceTask;
import io.openmessaging.connector.api.data.ConnectRecord;
-import io.openmessaging.connector.api.data.Converter;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -41,6 +41,8 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
+
+import io.openmessaging.connector.api.data.RecordConverter;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
@@ -417,11 +419,15 @@ public class Worker {
}
final Task task = (Task) taskClazz.getDeclaredConstructor().newInstance();
final String converterClazzName = keyValue.getString(RuntimeConfigDefine.SOURCE_RECORD_CONVERTER);
- Converter recordConverter = null;
+ RecordConverter recordConverter = null;
if (StringUtils.isNotEmpty(converterClazzName)) {
- Class converterClazz = Class.forName(converterClazzName);
- recordConverter = (Converter) converterClazz.newInstance();
+ recordConverter = Class.forName(converterClazzName)
+ .asSubclass(io.openmessaging.connector.api.data.RecordConverter.class)
+ .getDeclaredConstructor()
+ .newInstance();
+ recordConverter.configure(keyValue.getProperties());
}
+
if (isolationFlag) {
Plugin.compareAndSwapLoaders(loader);
}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerDirectTask.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerDirectTask.java
index 65c66ce..992c071 100644
--- a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerDirectTask.java
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerDirectTask.java
@@ -168,8 +168,14 @@ public class WorkerDirectTask implements WorkerTask {
public String getTaskName() {
return taskConfig.getString(RuntimeConfigDefine.TASK_ID);
}
-
- @Override public KeyValue configs() {
+
+ /**
+ * Get the configurations of current task.
+ *
+ * @return the configuration of current task.
+ */
+ @Override
+ public KeyValue configs() {
return taskConfig;
}
@@ -219,8 +225,13 @@ public class WorkerDirectTask implements WorkerTask {
@Override public String getTaskName() {
return null;
}
-
- @Override public KeyValue configs() {
+ /**
+ * Get the configurations of current task.
+ *
+ * @return the configuration of current task.
+ */
+ @Override
+ public KeyValue configs() {
return taskConfig;
}
});
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerSinkTask.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerSinkTask.java
index f649bed..5afaa24 100644
--- a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerSinkTask.java
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerSinkTask.java
@@ -21,14 +21,13 @@ import com.alibaba.fastjson.JSON;
import io.openmessaging.KeyValue;
import io.openmessaging.connector.api.component.task.sink.SinkTask;
import io.openmessaging.connector.api.data.ConnectRecord;
-import io.openmessaging.connector.api.data.Converter;
+import io.openmessaging.connector.api.data.RecordConverter;
import io.openmessaging.connector.api.data.RecordOffset;
import io.openmessaging.connector.api.data.RecordPartition;
-import io.openmessaging.connector.api.data.Schema;
+import io.openmessaging.connector.api.data.SchemaAndValue;
import io.openmessaging.connector.api.errors.ConnectException;
import io.openmessaging.connector.api.errors.RetriableException;
import io.openmessaging.internal.DefaultKeyValue;
-import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -59,7 +58,6 @@ import org.apache.rocketmq.connect.runtime.common.LoggerName;
import org.apache.rocketmq.connect.runtime.common.QueueState;
import org.apache.rocketmq.connect.runtime.config.RuntimeConfigDefine;
import org.apache.rocketmq.connect.runtime.config.SinkConnectorConfig;
-import org.apache.rocketmq.connect.runtime.converter.RocketMQConverter;
import org.apache.rocketmq.connect.runtime.errors.ErrorReporter;
import org.apache.rocketmq.connect.runtime.errors.RetryWithToleranceOperator;
import org.apache.rocketmq.connect.runtime.errors.WorkerErrorRecordReporter;
@@ -121,7 +119,7 @@ public class WorkerSinkTask implements WorkerTask {
/**
* A converter to parse sink data entry to object.
*/
- private Converter recordConverter;
+ private RecordConverter recordConverter;
private final ConcurrentHashMap<MessageQueue, Long> messageQueuesOffsetMap;
@@ -185,7 +183,7 @@ public class WorkerSinkTask implements WorkerTask {
public WorkerSinkTask(String connectorName,
SinkTask sinkTask,
ConnectKeyValue taskConfig,
- Converter recordConverter,
+ RecordConverter recordConverter,
DefaultMQPullConsumer consumer,
AtomicReference<WorkerState> workerState,
ConnectStatsManager connectStatsManager,
@@ -583,28 +581,33 @@ public class WorkerSinkTask implements WorkerTask {
private ConnectRecord convertToSinkDataEntry(MessageExt message) {
Map<String, String> properties = message.getProperties();
- Schema schema;
- Long timestamp;
- ConnectRecord sinkDataEntry = null;
- if (null == recordConverter || recordConverter instanceof RocketMQConverter) {
- String connectTimestamp = properties.get(RuntimeConfigDefine.CONNECT_TIMESTAMP);
- timestamp = StringUtils.isNotEmpty(connectTimestamp) ? Long.valueOf(connectTimestamp) : null;
- String connectSchema = properties.get(RuntimeConfigDefine.CONNECT_SCHEMA);
- schema = StringUtils.isNotEmpty(connectSchema) ? JSON.parseObject(connectSchema, Schema.class) : null;
- byte[] body = message.getBody();
- RecordPartition recordPartition = ConnectUtil.convertToRecordPartition(message.getTopic(), message.getBrokerName(), message.getQueueId());
-
- RecordOffset recordOffset = ConnectUtil.convertToRecordOffset(message.getQueueOffset());
+ ConnectRecord sinkDataEntry;
- String bodyStr = new String(body, StandardCharsets.UTF_8);
- sinkDataEntry = new ConnectRecord(recordPartition, recordOffset, timestamp, schema, bodyStr);
-
- } else {
+ // start convert
+ if (recordConverter == null) {
final byte[] messageBody = message.getBody();
String s = new String(messageBody);
sinkDataEntry = JSON.parseObject(s, ConnectRecord.class);
+ } else {
+ // timestamp
+ String connectTimestamp = properties.get(RuntimeConfigDefine.CONNECT_TIMESTAMP);
+ Long timestamp = StringUtils.isNotEmpty(connectTimestamp) ? Long.valueOf(connectTimestamp) : null;
+
+ // partition and offset
+ RecordPartition recordPartition = ConnectUtil.convertToRecordPartition(message.getTopic(), message.getBrokerName(), message.getQueueId());
+ RecordOffset recordOffset = ConnectUtil.convertToRecordOffset(message.getQueueOffset());
+
+ // convert
+ SchemaAndValue schemaAndValue = retryWithToleranceOperator.execute(() -> recordConverter.toConnectData(message.getTopic(), message.getBody()),
+ ErrorReporter.Stage.CONVERTER, recordConverter.getClass());
+ sinkDataEntry = new ConnectRecord(recordPartition, recordOffset, timestamp, schemaAndValue.schema(), schemaAndValue.value());
}
+ // add extension
+ addExtension(properties, sinkDataEntry);
+ return sinkDataEntry;
+ }
+ private void addExtension(Map<String, String> properties, ConnectRecord sinkDataEntry) {
KeyValue keyValue = new DefaultKeyValue();
if (MapUtils.isNotEmpty(properties)) {
for (Map.Entry<String, String> entry : properties.entrySet()) {
@@ -618,8 +621,6 @@ public class WorkerSinkTask implements WorkerTask {
}
}
sinkDataEntry.addExtension(keyValue);
-
- return sinkDataEntry;
}
@Override
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerSourceTask.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerSourceTask.java
index 1271df7..6711dc5 100644
--- a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerSourceTask.java
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerSourceTask.java
@@ -24,21 +24,13 @@ import io.openmessaging.KeyValue;
import io.openmessaging.connector.api.component.task.source.SourceTask;
import io.openmessaging.connector.api.component.task.source.SourceTaskContext;
import io.openmessaging.connector.api.data.ConnectRecord;
-import io.openmessaging.connector.api.data.Converter;
+import io.openmessaging.connector.api.data.RecordConverter;
import io.openmessaging.connector.api.data.RecordOffset;
import io.openmessaging.connector.api.data.RecordPartition;
import io.openmessaging.connector.api.data.RecordPosition;
import io.openmessaging.connector.api.errors.ConnectException;
import io.openmessaging.connector.api.errors.RetriableException;
import io.openmessaging.connector.api.storage.OffsetStorageReader;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.exception.MQClientException;
@@ -50,7 +42,7 @@ import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.connect.runtime.common.ConnectKeyValue;
import org.apache.rocketmq.connect.runtime.common.LoggerName;
import org.apache.rocketmq.connect.runtime.config.RuntimeConfigDefine;
-import org.apache.rocketmq.connect.runtime.converter.RocketMQConverter;
+import org.apache.rocketmq.connect.runtime.errors.ErrorReporter;
import org.apache.rocketmq.connect.runtime.errors.RetryWithToleranceOperator;
import org.apache.rocketmq.connect.runtime.service.PositionManagementService;
import org.apache.rocketmq.connect.runtime.stats.ConnectStatsManager;
@@ -62,6 +54,15 @@ import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+
import static org.apache.rocketmq.connect.runtime.connectorwrapper.WorkerSinkTask.TOPIC;
/**
@@ -109,7 +110,7 @@ public class WorkerSourceTask implements WorkerTask {
/**
* A converter to parse source data entry to byte[].
*/
- private Converter recordConverter;
+ private RecordConverter recordConverter;
private final AtomicReference<WorkerState> workerState;
@@ -133,16 +134,16 @@ public class WorkerSourceTask implements WorkerTask {
}
public WorkerSourceTask(String connectorName,
- SourceTask sourceTask,
- ConnectKeyValue taskConfig,
- PositionManagementService positionManagementService,
- Converter recordConverter,
- DefaultMQProducer producer,
- AtomicReference<WorkerState> workerState,
- ConnectStatsManager connectStatsManager,
- ConnectStatsService connectStatsService,
- TransformChain<ConnectRecord> transformChain,
- RetryWithToleranceOperator retryWithToleranceOperator) {
+ SourceTask sourceTask,
+ ConnectKeyValue taskConfig,
+ PositionManagementService positionManagementService,
+ RecordConverter recordConverter,
+ DefaultMQProducer producer,
+ AtomicReference<WorkerState> workerState,
+ ConnectStatsManager connectStatsManager,
+ ConnectStatsService connectStatsService,
+ TransformChain<ConnectRecord> transformChain,
+ RetryWithToleranceOperator retryWithToleranceOperator) {
this.connectorName = connectorName;
this.sourceTask = sourceTask;
this.taskConfig = taskConfig;
@@ -276,7 +277,7 @@ public class WorkerSourceTask implements WorkerTask {
public void cleanup() {
log.info("Cleaning a task, current state {}, destination state {}", state.get().name(), WorkerTaskState.TERMINATED.name());
if (state.compareAndSet(WorkerTaskState.STOPPED, WorkerTaskState.TERMINATED) ||
- state.compareAndSet(WorkerTaskState.ERROR, WorkerTaskState.TERMINATED)) {
+ state.compareAndSet(WorkerTaskState.ERROR, WorkerTaskState.TERMINATED)) {
log.info("Cleaning a task success");
} else {
log.error("[BUG] cleaning a task but it's not in STOPPED or ERROR state");
@@ -321,25 +322,27 @@ public class WorkerSourceTask implements WorkerTask {
throw new ConnectException("source connect lack of topic config");
}
sourceMessage.setTopic(topic);
- putExtendMsgProperty(sourceDataEntry, sourceMessage, topic);
- if (null == recordConverter || recordConverter instanceof RocketMQConverter) {
- Object payload = sourceDataEntry.getData();
- if (null != payload) {
- final byte[] messageBody = (String.valueOf(payload)).getBytes();
- if (messageBody.length > RuntimeConfigDefine.MAX_MESSAGE_SIZE) {
- log.error("Send record, message size is greater than {} bytes, sourceDataEntry: {}", RuntimeConfigDefine.MAX_MESSAGE_SIZE, JSON.toJSONString(sourceDataEntry));
- continue;
- }
- sourceMessage.setBody(messageBody);
+ // converter
+ if (recordConverter == null) {
+ final byte[] messageBody = JSON.toJSONString(sourceDataEntry, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue).getBytes();
+ if (messageBody.length > RuntimeConfigDefine.MAX_MESSAGE_SIZE) {
+ log.error("Send record, message size is greater than {} bytes, sourceDataEntry: {}", RuntimeConfigDefine.MAX_MESSAGE_SIZE, JSON.toJSONString(sourceDataEntry));
+ continue;
}
+ sourceMessage.setBody(messageBody);
} else {
- final byte[] messageBody = JSON.toJSONString(sourceDataEntry, SerializerFeature.DisableCircularReferenceDetect).getBytes();
+ String finalTopic = topic;
+ byte[] messageBody = retryWithToleranceOperator.execute(() -> recordConverter.fromConnectData(finalTopic, sourceDataEntry.getSchema(), sourceDataEntry.getData()),
+ ErrorReporter.Stage.CONVERTER, recordConverter.getClass());
if (messageBody.length > RuntimeConfigDefine.MAX_MESSAGE_SIZE) {
log.error("Send record, message size is greater than {} bytes, sourceDataEntry: {}", RuntimeConfigDefine.MAX_MESSAGE_SIZE, JSON.toJSONString(sourceDataEntry));
continue;
}
sourceMessage.setBody(messageBody);
}
+ // put extend msg property
+ putExtendMsgProperty(sourceDataEntry, sourceMessage, topic);
+
try {
producer.send(sourceMessage, new SendCallback() {
@Override
@@ -432,8 +435,8 @@ public class WorkerSourceTask implements WorkerTask {
StringBuilder sb = new StringBuilder();
sb.append("connectorName:" + connectorName)
- .append("\nConfigs:" + JSON.toJSONString(taskConfig))
- .append("\nState:" + state.get().toString());
+ .append("\nConfigs:" + JSON.toJSONString(taskConfig))
+ .append("\nState:" + state.get().toString());
return sb.toString();
}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteBufferConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteBufferConverter.java
index ce3f315..e509305 100644
--- a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteBufferConverter.java
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteBufferConverter.java
@@ -33,4 +33,4 @@ public class ByteBufferConverter implements Converter<ByteBuffer> {
@Override public ByteBuffer byteToObject(byte[] bytes) {
return ByteBuffer.wrap(bytes);
}
-}
+}
\ No newline at end of file
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteConverter.java
index 2b6e191..6387d3e 100644
--- a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteConverter.java
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteConverter.java
@@ -33,4 +33,4 @@ public class ByteConverter implements Converter<byte[]> {
public byte[] byteToObject(byte[] bytes) {
return bytes;
}
-}
+}
\ No newline at end of file
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteMapConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteMapConverter.java
index 55fa0fe..ced7b24 100644
--- a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteMapConverter.java
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/ByteMapConverter.java
@@ -70,4 +70,4 @@ public class ByteMapConverter implements Converter<Map<ByteBuffer, ByteBuffer>>
return resultMap;
}
-}
+}
\ No newline at end of file
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/ByteArrayConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/ByteArrayConverter.java
new file mode 100644
index 0000000..a6ca140
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/ByteArrayConverter.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.FieldType;
+import io.openmessaging.connector.api.data.RecordConverter;
+import io.openmessaging.connector.api.data.Schema;
+import io.openmessaging.connector.api.data.SchemaAndValue;
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import io.openmessaging.connector.api.errors.ConnectException;
+
+import java.util.Map;
+
+
+/**
+ * byte array converter
+ */
+public class ByteArrayConverter implements RecordConverter {
+
+ /**
+ * Configure this class.
+ *
+ * @param configs configs in key/value pairs
+ */
+ @Override
+ public void configure(Map configs) {
+ // config
+ }
+
+ @Override
+ public byte[] fromConnectData(String topic, Schema schema, Object value) {
+ if (schema != null && schema.getFieldType() != FieldType.BYTES) {
+ throw new ConnectException("Invalid schema type for ByteArrayConverter: " + schema.getFieldType().toString());
+ }
+ if (value != null && !(value instanceof byte[])) {
+ throw new ConnectException("ByteArrayConverter is not compatible with objects of type " + value.getClass());
+ }
+ return (byte[]) value;
+ }
+
+ @Override
+ public SchemaAndValue toConnectData(String topic, byte[] value) {
+ return new SchemaAndValue(SchemaBuilder.bytes().build(), value);
+ }
+
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/DoubleConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/DoubleConverter.java
new file mode 100644
index 0000000..36dd77e
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/DoubleConverter.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import org.apache.rocketmq.connect.runtime.serialization.DoubleDeserializer;
+import org.apache.rocketmq.connect.runtime.serialization.DoubleSerializer;
+
+
+/**
+ * double converter
+ */
+public class DoubleConverter extends NumberConverter<Double> {
+
+ public DoubleConverter() {
+ super("double", SchemaBuilder.float64().build(), new DoubleSerializer(), new DoubleDeserializer());
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/FloatConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/FloatConverter.java
new file mode 100644
index 0000000..077a5e9
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/FloatConverter.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import org.apache.rocketmq.connect.runtime.serialization.FloatDeserializer;
+import org.apache.rocketmq.connect.runtime.serialization.FloatSerializer;
+
+/**
+ * float converter
+ */
+public class FloatConverter extends NumberConverter<Float> {
+
+ public FloatConverter() {
+ super("float", SchemaBuilder.float32().build(), new FloatSerializer(), new FloatDeserializer());
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/IntegerConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/IntegerConverter.java
new file mode 100644
index 0000000..3bdeafd
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/IntegerConverter.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import org.apache.rocketmq.connect.runtime.serialization.IntegerDeserializer;
+import org.apache.rocketmq.connect.runtime.serialization.IntegerSerializer;
+
+/**
+ * integer converter
+ */
+public class IntegerConverter extends NumberConverter<Integer> {
+
+ public IntegerConverter() {
+ super("integer", SchemaBuilder.int32().build(), new IntegerSerializer(), new IntegerDeserializer());
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/LongConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/LongConverter.java
new file mode 100644
index 0000000..788f4c0
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/LongConverter.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import org.apache.rocketmq.connect.runtime.serialization.LongDeserializer;
+import org.apache.rocketmq.connect.runtime.serialization.LongSerializer;
+
+/**
+ * long converter
+ */
+public class LongConverter extends NumberConverter<Long> {
+
+ public LongConverter() {
+ super("long", SchemaBuilder.int64().build(), new LongSerializer(), new LongDeserializer());
+ }
+
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/NumberConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/NumberConverter.java
new file mode 100644
index 0000000..4b8a22b
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/NumberConverter.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.RecordConverter;
+import io.openmessaging.connector.api.data.Schema;
+import io.openmessaging.connector.api.data.SchemaAndValue;
+import io.openmessaging.connector.api.errors.ConnectException;
+import org.apache.rocketmq.connect.runtime.serialization.Deserializer;
+import org.apache.rocketmq.connect.runtime.serialization.Serializer;
+
+import java.util.Map;
+
+
+/**
+ * number converter
+ *
+ * @param <T>
+ */
+abstract class NumberConverter<T extends Number> implements RecordConverter {
+
+ private final Serializer<T> serializer;
+ private final Deserializer<T> deserializer;
+ private final String typeName;
+ private final Schema schema;
+
+ /**
+ * Create the converter.
+ *
+ * @param typeName the displayable name of the type; may not be null
+ * @param schema the optional schema to be used for all deserialized forms; may not be null
+ * @param serializer the serializer; may not be null
+ * @param deserializer the deserializer; may not be null
+ */
+ protected NumberConverter(String typeName, Schema schema, Serializer<T> serializer, Deserializer<T> deserializer) {
+ this.typeName = typeName;
+ this.schema = schema;
+ this.serializer = serializer;
+ this.deserializer = deserializer;
+ assert this.serializer != null;
+ assert this.deserializer != null;
+ assert this.typeName != null;
+ assert this.schema != null;
+ }
+
+ @Override
+ public void configure(Map<String, ?> configs) {
+ serializer.configure(configs);
+ deserializer.configure(configs);
+ }
+
+ @Override
+ public byte[] fromConnectData(String topic, Schema schema, Object value) {
+ try {
+ return serializer.serialize(topic, value == null ? null : cast(value));
+ } catch (Exception e) {
+ throw new io.openmessaging.connector.api.errors.ConnectException("Failed to serialize to " + typeName + " (was " + value.getClass() + "): ", e);
+ }
+ }
+
+ @Override
+ public SchemaAndValue toConnectData(String topic, byte[] value) {
+ try {
+ return new SchemaAndValue(schema, deserializer.deserialize(topic, value));
+ } catch (RuntimeException e) {
+ throw new ConnectException("Failed to deserialize " + typeName + ": ", e);
+ }
+ }
+
+ protected T cast(Object value) {
+ return (T) value;
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/ShortConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/ShortConverter.java
new file mode 100644
index 0000000..287e745
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/ShortConverter.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import org.apache.rocketmq.connect.runtime.serialization.ShortDeserializer;
+import org.apache.rocketmq.connect.runtime.serialization.ShortSerializer;
+
+/**
+ * short converter
+ */
+public class ShortConverter extends NumberConverter<Short> {
+
+ public ShortConverter() {
+ super("short", SchemaBuilder.int16().build(), new ShortSerializer(), new ShortDeserializer());
+ }
+
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/StringConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/StringConverter.java
new file mode 100644
index 0000000..0bb7328
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/StringConverter.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.RecordConverter;
+import io.openmessaging.connector.api.data.Schema;
+import io.openmessaging.connector.api.data.SchemaAndValue;
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import io.openmessaging.connector.api.errors.ConnectException;
+import org.apache.rocketmq.connect.runtime.serialization.StringDeserializer;
+import org.apache.rocketmq.connect.runtime.serialization.StringSerializer;
+
+import java.util.Map;
+
+
+/**
+ * string converter
+ */
+public class StringConverter implements RecordConverter {
+
+ private final StringSerializer serializer = new StringSerializer();
+ private final StringDeserializer deserializer = new StringDeserializer();
+
+ /**
+ * Configure this class.
+ *
+ * @param configs configs in key/value pairs
+ */
+ @Override
+ public void configure(Map<String, ?> configs) {
+ serializer.configure(configs);
+ deserializer.configure(configs);
+ }
+
+ /**
+ * Convert a rocketmq Connect data object to a native object for serialization.
+ *
+ * @param topic the topic associated with the data
+ * @param schema the schema for the value
+ * @param value the value to convert
+ * @return the serialized value
+ */
+ @Override
+ public byte[] fromConnectData(String topic, Schema schema, Object value) {
+ try {
+ return serializer.serialize(topic, value == null ? null : value.toString());
+ } catch (Exception e) {
+ throw new ConnectException("Failed to serialize to a string: ", e);
+ }
+ }
+
+ /**
+ * Convert a native object to a Rocketmq Connect data object.
+ */
+ @Override
+ public SchemaAndValue toConnectData(String topic, byte[] value) {
+ try {
+ return new SchemaAndValue(SchemaBuilder.string().build(), deserializer.deserialize(topic, value));
+ } catch (Exception e) {
+ throw new ConnectException("Failed to deserialize string: ", e);
+ }
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/json/DecimalFormat.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/json/DecimalFormat.java
new file mode 100644
index 0000000..c2a25ef
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/json/DecimalFormat.java
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record.json;
+
+
+/**
+ * decimal format
+ */
+public enum DecimalFormat {
+
+ /**
+ * Serializes the JSON Decimal as a base-64 string. For example, serializing the value
+ * `10.2345` with the BASE64 setting will result in `"D3J5"`.
+ */
+ BASE64,
+
+ /**
+ * Serializes the JSON Decimal as a JSON number. For example, serializing the value
+ * `10.2345` with the NUMERIC setting will result in `10.2345`.
+ */
+ NUMERIC
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/json/JsonConverter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/json/JsonConverter.java
new file mode 100644
index 0000000..743dcdc
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/json/JsonConverter.java
@@ -0,0 +1,800 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record.json;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.alibaba.fastjson.util.TypeUtils;
+import io.openmessaging.connector.api.data.Field;
+import io.openmessaging.connector.api.data.FieldType;
+import io.openmessaging.connector.api.data.RecordConverter;
+import io.openmessaging.connector.api.data.Schema;
+import io.openmessaging.connector.api.data.SchemaAndValue;
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import io.openmessaging.connector.api.data.Struct;
+import io.openmessaging.connector.api.data.logical.Date;
+import io.openmessaging.connector.api.data.logical.Decimal;
+import io.openmessaging.connector.api.data.logical.Time;
+import io.openmessaging.connector.api.data.logical.Timestamp;
+import io.openmessaging.connector.api.errors.ConnectException;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.rocketmq.connect.runtime.common.LoggerName;
+import org.apache.rocketmq.connect.runtime.common.cache.Cache;
+import org.apache.rocketmq.connect.runtime.common.cache.LRUCache;
+import org.apache.rocketmq.connect.runtime.serialization.JsonDeserializer;
+import org.apache.rocketmq.connect.runtime.serialization.JsonSerializer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.math.BigDecimal;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+
+
+/**
+ * json converter for fastjson
+ */
+public class JsonConverter implements RecordConverter {
+ private static final Logger log = LoggerFactory.getLogger(LoggerName.ROCKETMQ_RUNTIME);
+
+
+ private static final Map<FieldType, JsonToConnectTypeConverter> TO_CONNECT_CONVERTERS = new EnumMap<>(FieldType.class);
+
+ {
+ TO_CONNECT_CONVERTERS.put(FieldType.BOOLEAN, new JsonToConnectTypeConverter<Boolean>() {
+ @Override
+ public Boolean convert(Schema schema, Object value) {
+ return Boolean.valueOf(value.toString());
+ }
+ });
+ TO_CONNECT_CONVERTERS.put(FieldType.INT8, new JsonToConnectTypeConverter<Byte>() {
+ @Override
+ public Byte convert(Schema schema, Object value) {
+ return Byte.valueOf(value.toString());
+ }
+ });
+ TO_CONNECT_CONVERTERS.put(FieldType.INT16, new JsonToConnectTypeConverter<Short>() {
+ @Override
+ public Short convert(Schema schema, Object value) {
+ return Short.valueOf(value.toString());
+ }
+ });
+ TO_CONNECT_CONVERTERS.put(FieldType.INT32, new JsonToConnectTypeConverter<Integer>() {
+ @Override
+ public Integer convert(Schema schema, Object value) {
+ return Integer.valueOf(value.toString());
+ }
+ });
+ TO_CONNECT_CONVERTERS.put(FieldType.INT64, new JsonToConnectTypeConverter<Long>() {
+ @Override
+ public Long convert(Schema schema, Object value) {
+ return Long.valueOf(value.toString());
+ }
+ });
+ TO_CONNECT_CONVERTERS.put(FieldType.FLOAT32, new JsonToConnectTypeConverter<Float>() {
+ @Override
+ public Float convert(Schema schema, Object value) {
+ return (Float) value;
+ }
+ });
+ TO_CONNECT_CONVERTERS.put(FieldType.FLOAT64, new JsonToConnectTypeConverter<Double>() {
+ @Override
+ public Double convert(Schema schema, Object value) {
+ if (value instanceof BigDecimal) {
+ return Double.parseDouble(value.toString());
+ }
+ return (Double) value;
+ }
+ });
+ TO_CONNECT_CONVERTERS.put(FieldType.BYTES, new JsonToConnectTypeConverter<byte[]>() {
+ @Override
+ public byte[] convert(Schema schema, Object value) {
+ if (value instanceof String) {
+ return TypeUtils.castToBytes(value.toString());
+ }
+ return (byte[]) value;
+ }
+ });
+ TO_CONNECT_CONVERTERS.put(FieldType.STRING, new JsonToConnectTypeConverter<String>() {
+ @Override
+ public String convert(Schema schema, Object value) {
+ return String.valueOf(value);
+ }
+ });
+ TO_CONNECT_CONVERTERS.put(FieldType.ARRAY, new JsonToConnectTypeConverter<List<Object>>() {
+ @Override
+ public List<Object> convert(Schema schema, Object value) {
+ Schema elemSchema = schema == null ? null : schema.getValueSchema();
+ List<Object> values = (List<Object>) value;
+ List<Object> result = new ArrayList<>();
+ for (Object elem : values) {
+ result.add(convertToConnect(elemSchema, elem));
+ }
+ return result;
+ }
+ });
+ TO_CONNECT_CONVERTERS.put(FieldType.MAP, new JsonToConnectTypeConverter<Map<Object, Object>>() {
+ @Override
+ public Map<Object, Object> convert(Schema schema, Object value) {
+ Schema keySchema = schema == null ? null : schema.getKeySchema();
+ Schema valueSchema = schema == null ? null : schema.getValueSchema();
+ Map<Object, Object> result = new HashMap<>();
+ if (schema == null || keySchema.getFieldType() == FieldType.STRING) {
+ Map<String, Object> fieldIt = (Map<String, Object>) value;
+ fieldIt.forEach((k, v) -> {
+ result.put(k, convertToConnect(valueSchema, v));
+ });
+ } else {
+ if (!(value instanceof JSONArray)) {
+ throw new ConnectException("Maps with non-string fields should be encoded as JSON array of tuples, but found " + JSON.toJSONString(value));
+ }
+ JSONArray array = (JSONArray) value;
+ for (Object entry : array.stream().toArray()) {
+ if (!(value instanceof JSONArray)) {
+ throw new ConnectException("Found invalid map entry instead of array tuple: " + JSON.toJSONString(entry));
+ }
+ JSONArray entryArray = (JSONArray) entry;
+ if (entryArray.toArray().length != 2) {
+ throw new ConnectException("Found invalid map entry, expected length 2 but found :" + entryArray.toArray().length);
+ }
+ result.put(
+ convertToConnect(keySchema, entryArray.toArray()[0]),
+ convertToConnect(valueSchema, entryArray.toArray()[1]));
+ }
+ }
+ return result;
+ }
+ });
+ TO_CONNECT_CONVERTERS.put(FieldType.STRUCT, new JsonToConnectTypeConverter() {
+ @Override
+ public Object convert(Schema schema, Object value) {
+ Struct result = new Struct(schema);
+ JSONObject obj = (JSONObject) value;
+ for (Field field : schema.getFields()) {
+ result.put(field, convertToConnect(field.getSchema(), obj.get(field.getName())));
+ }
+ return result;
+ }
+ });
+ }
+
+ // Convert values in Kafka Connect form into/from their logical types. These logical converters are discovered by logical type
+ // names specified in the field
+ private static final HashMap<String, LogicalTypeConverter> LOGICAL_CONVERTERS = new HashMap<>();
+
+ static {
+ LOGICAL_CONVERTERS.put(Decimal.LOGICAL_NAME, new LogicalTypeConverter() {
+ @Override
+ public Object toJson(final Schema schema, final Object value, final JsonConverterConfig config) {
+ if (!(value instanceof BigDecimal)) {
+ throw new ConnectException("Invalid type for Decimal, expected BigDecimal but was " + value.getClass());
+ }
+ final BigDecimal decimal = (BigDecimal) value;
+ switch (config.decimalFormat()) {
+ case NUMERIC:
+ return decimal;
+ case BASE64:
+ return Decimal.fromLogical(schema, decimal);
+ default:
+ throw new ConnectException("Unexpected " + JsonConverterConfig.DECIMAL_FORMAT_CONFIG + ": " + config.decimalFormat());
+ }
+ }
+
+ @Override
+ public Object toConnect(final Schema schema, final Object value) {
+ if (value instanceof BigDecimal) {
+ return (BigDecimal) value;
+ }
+ if (value instanceof byte[]) {
+ try {
+ return Decimal.toLogical(schema, (byte[]) value);
+ } catch (Exception e) {
+ throw new ConnectException("Invalid bytes for Decimal field", e);
+ }
+ }
+ if (value instanceof String) {
+ try {
+ return Decimal.toLogical(schema, TypeUtils.castToBytes((String) value));
+ } catch (Exception e) {
+ throw new ConnectException("Invalid bytes for Decimal field", e);
+ }
+ }
+ throw new ConnectException("Invalid type for Decimal, underlying representation should be numeric or bytes but was " + value);
+ }
+ });
+
+ LOGICAL_CONVERTERS.put(Date.LOGICAL_NAME, new LogicalTypeConverter() {
+ @Override
+ public Object toJson(final Schema schema, final Object value, final JsonConverterConfig config) {
+ if (!(value instanceof java.util.Date)) {
+ throw new ConnectException("Invalid type for Date, expected Date but was " + value.getClass());
+ }
+ return Date.fromLogical(schema, (java.util.Date) value);
+ }
+
+ @Override
+ public Object toConnect(final Schema schema, final Object value) {
+ if (!(value instanceof Integer)) {
+ throw new ConnectException("Invalid type for Date, underlying representation should be integer but was " + value);
+ }
+ return Date.toLogical(schema, (Integer) value);
+ }
+ });
+
+ LOGICAL_CONVERTERS.put(Time.LOGICAL_NAME, new LogicalTypeConverter() {
+ @Override
+ public Object toJson(final Schema schema, final Object value, final JsonConverterConfig config) {
+ if (!(value instanceof java.util.Date)) {
+ throw new ConnectException("Invalid type for Time, expected Date but was " + value.getClass());
+ }
+ return Time.fromLogical(schema, (java.util.Date) value);
+ }
+
+ @Override
+ public Object toConnect(final Schema schema, final Object value) {
+ if (!(value instanceof Integer)) {
+ throw new ConnectException("Invalid type for Time, underlying representation should be integer but was " + value);
+ }
+ return Time.toLogical(schema, ((Integer) value).intValue());
+ }
+ });
+
+ LOGICAL_CONVERTERS.put(Timestamp.LOGICAL_NAME, new LogicalTypeConverter() {
+ @Override
+ public Object toJson(final Schema schema, final Object value, final JsonConverterConfig config) {
+ if (!(value instanceof java.util.Date)) {
+ throw new ConnectException("Invalid type for Timestamp, expected Date but was " + value.getClass());
+ }
+ return Timestamp.fromLogical(schema, (java.util.Date) value);
+ }
+
+ @Override
+ public Object toConnect(final Schema schema, final Object value) {
+ if (value instanceof Number) {
+ return Timestamp.toLogical(schema, Long.valueOf(value.toString()));
+ }
+ throw new ConnectException("Invalid type for Timestamp, underlying representation should be integral but was " + value);
+ }
+ });
+ }
+
+
+ private JsonDeserializer deserializer = new JsonDeserializer();
+ private JsonSerializer serializer = new JsonSerializer();
+ public JsonConverterConfig converterConfig;
+ private Cache<Schema, JSONObject> fromConnectSchemaCache;
+ private Cache<JSONObject, Schema> toConnectSchemaCache;
+
+ /**
+ * Configure this class.
+ *
+ * @param configs configs in key/value pairs
+ */
+ @Override
+ public void configure(Map<String, ?> configs) {
+ converterConfig = new JsonConverterConfig(configs);
+ fromConnectSchemaCache = new LRUCache<>(converterConfig.cacheSize());
+ toConnectSchemaCache = new LRUCache<>(converterConfig.cacheSize());
+ }
+
+ /**
+ * Convert a rocketmq Connect data object to a native object for serialization.
+ *
+ * @param topic the topic associated with the data
+ * @param schema the schema for the value
+ * @param value the value to convert
+ * @return the serialized value
+ */
+ @Override
+ public byte[] fromConnectData(String topic, Schema schema, Object value) {
+ if (schema == null && value == null) {
+ return null;
+ }
+ Object jsonValue = converterConfig.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value);
+ try {
+ return serializer.serialize(topic, jsonValue);
+ } catch (Exception e) {
+ throw new ConnectException("Converting Kafka Connect data to byte[] failed due to serialization error: ", e);
+ }
+ }
+
+ /**
+ * Convert a native object to a Rocketmq Connect data object.
+ *
+ * @param topic the topic associated with the data
+ * @param value the value to convert
+ * @return an object containing the {@link Schema} and the converted value
+ */
+ @Override
+ public SchemaAndValue toConnectData(String topic, byte[] value) {
+ // This handles a tombstone message
+ if (value == null) {
+ return SchemaAndValue.NULL;
+ }
+ Object jsonValue;
+ try {
+ jsonValue = deserializer.deserialize(topic, value);
+ } catch (Exception e) {
+ throw new ConnectException("Converting byte[] to Kafka Connect data failed due to serialization error: ", e);
+ }
+ JSONObject newJsonValue;
+ if (!converterConfig.schemasEnabled()) {
+ // schema disabled
+ JSONObject envelope = new JSONObject();
+ envelope.put(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME, null);
+ envelope.put(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME, jsonValue);
+ newJsonValue = envelope;
+ } else {
+ // schema enabled
+ newJsonValue = (JSONObject) jsonValue;
+ }
+ Object jsonSchema = newJsonValue.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME);
+ Schema schema = asConnectSchema(jsonSchema == null ? null : (JSONObject) jsonSchema);
+ return new SchemaAndValue(
+ schema,
+ convertToConnect(schema, newJsonValue.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME))
+ );
+ }
+
+
+ /**
+ * convert to json with envelope
+ *
+ * @param schema
+ * @param value
+ * @return
+ */
+ private JSONObject convertToJsonWithEnvelope(Schema schema, Object value) {
+ return new JsonSchema.Envelope(
+ asJsonSchema(schema),
+ convertToJson(schema, value)
+ ).toJsonNode();
+ }
+
+ /**
+ * convert to json without envelop
+ *
+ * @param schema
+ * @param value
+ * @return
+ */
+ private Object convertToJsonWithoutEnvelope(Schema schema, Object value) {
+ return convertToJson(schema, value);
+ }
+
+
+ private interface JsonToConnectTypeConverter<Output> {
+ Output convert(Schema schema, Object value);
+ }
+
+ private interface LogicalTypeConverter {
+ Object toJson(Schema schema, Object value, JsonConverterConfig config);
+
+ Object toConnect(Schema schema, Object value);
+ }
+
+
+ /**
+ * convert ConnectRecord schema to json schema
+ *
+ * @param schema
+ * @return
+ */
+ public JSONObject asJsonSchema(Schema schema) {
+ if (schema == null) {
+ return null;
+ }
+ // from cached
+ JSONObject cached = fromConnectSchemaCache.get(schema);
+ if (cached != null) {
+ return cached.clone();
+ }
+
+ JSONObject jsonSchema;
+ // convert field type name
+ switch (schema.getFieldType()) {
+ case BOOLEAN:
+ jsonSchema = JsonSchema.BOOLEAN_SCHEMA();
+ break;
+ case BYTES:
+ jsonSchema = JsonSchema.BYTES_SCHEMA();
+ break;
+ case FLOAT64:
+ jsonSchema = JsonSchema.DOUBLE_SCHEMA();
+ break;
+ case FLOAT32:
+ jsonSchema = JsonSchema.FLOAT_SCHEMA();
+ break;
+ case INT8:
+ jsonSchema = JsonSchema.INT8_SCHEMA();
+ break;
+ case INT16:
+ jsonSchema = JsonSchema.INT16_SCHEMA();
+ break;
+ case INT32:
+ jsonSchema = JsonSchema.INT32_SCHEMA();
+ break;
+ case INT64:
+ jsonSchema = JsonSchema.INT64_SCHEMA();
+ break;
+ case STRING:
+ jsonSchema = JsonSchema.STRING_SCHEMA();
+ break;
+ case ARRAY:
+ jsonSchema = new JSONObject();
+ jsonSchema.put(JsonSchema.SCHEMA_TYPE_FIELD_NAME, JsonSchema.ARRAY_TYPE_NAME);
+ jsonSchema.put(JsonSchema.ARRAY_ITEMS_FIELD_NAME, asJsonSchema(schema.getValueSchema()));
+ break;
+ case MAP:
+ jsonSchema = new JSONObject();
+ jsonSchema.put(JsonSchema.SCHEMA_TYPE_FIELD_NAME, JsonSchema.MAP_TYPE_NAME);
+ jsonSchema.put(JsonSchema.MAP_KEY_FIELD_NAME, asJsonSchema(schema.getKeySchema()));
+ jsonSchema.put(JsonSchema.MAP_VALUE_FIELD_NAME, asJsonSchema(schema.getValueSchema()));
+ break;
+ case STRUCT:
+ jsonSchema = new JSONObject(new ConcurrentHashMap<>());
+ jsonSchema.put(JsonSchema.SCHEMA_TYPE_FIELD_NAME, JsonSchema.STRUCT_TYPE_NAME);
+ // field list
+ JSONArray fields = new JSONArray();
+ for (Field field : schema.getFields()) {
+ String fieldName = field.getName();
+ JSONObject fieldJsonSchema = asJsonSchema(field.getSchema());
+ fieldJsonSchema.put(JsonSchema.STRUCT_FIELD_NAME_FIELD_NAME, fieldName);
+ fields.add(fieldJsonSchema);
+ }
+ jsonSchema.put(JsonSchema.STRUCT_FIELDS_FIELD_NAME, fields);
+ break;
+ default:
+ throw new ConnectException("Couldn't translate unsupported schema type " + schema + ".");
+ }
+
+ // optional
+ jsonSchema.put(JsonSchema.SCHEMA_OPTIONAL_FIELD_NAME, schema.isOptional());
+
+ // name
+ if (schema.getName() != null) {
+ jsonSchema.put(JsonSchema.SCHEMA_NAME_FIELD_NAME, schema.getName());
+ }
+ // version
+ if (schema.getVersion() != null) {
+ jsonSchema.put(JsonSchema.SCHEMA_VERSION_FIELD_NAME, schema.getVersion());
+ }
+
+ // doc
+ if (schema.getDoc() != null) {
+ jsonSchema.put(JsonSchema.SCHEMA_DOC_FIELD_NAME, schema.getDoc());
+ }
+
+ // parameters
+ if (schema.getParameters() != null) {
+ JSONObject jsonSchemaParams = new JSONObject();
+ for (Map.Entry<String, String> prop : schema.getParameters().entrySet()) {
+ jsonSchemaParams.put(prop.getKey(), prop.getValue());
+ }
+ jsonSchema.put(JsonSchema.SCHEMA_PARAMETERS_FIELD_NAME, jsonSchemaParams);
+ }
+
+ // default value
+ if (schema.getDefaultValue() != null) {
+ jsonSchema.put(JsonSchema.SCHEMA_DEFAULT_FIELD_NAME, convertToJson(schema, schema.getDefaultValue()));
+ }
+ // add cache
+ fromConnectSchemaCache.put(schema, jsonSchema);
+ return jsonSchema;
+ }
+
+
+ /**
+ * Convert this object, in the org.apache.kafka.connect.data format, into a JSON object, returning both the schema
+ * and the converted object.
+ */
+ private Object convertToJson(Schema schema, Object value) {
+ if (value == null) {
+ if (schema == null) {
+ return null;
+ }
+ if (schema.getDefaultValue() != null) {
+ return convertToJson(schema, schema.getDefaultValue());
+ }
+ if (schema.isOptional()) {
+ return null;
+ }
+ throw new ConnectException("Conversion error: null value for field that is required and has no default value");
+ }
+
+ if (schema != null && schema.getName() != null) {
+ LogicalTypeConverter logicalConverter = LOGICAL_CONVERTERS.get(schema.getName());
+ if (logicalConverter != null) {
+ if (value == null) {
+ return null;
+ } else {
+ return logicalConverter.toJson(schema, value, converterConfig);
+ }
+ }
+ }
+
+ try {
+ final FieldType schemaType;
+ if (schema == null) {
+ schemaType = Schema.schemaType(value.getClass());
+ if (schemaType == null) {
+ throw new ConnectException("Java class " + value.getClass() + " does not have corresponding schema type.");
+ }
+ } else {
+ schemaType = schema.getFieldType();
+ }
+
+ switch (schemaType) {
+ case INT8:
+ case INT16:
+ case INT32:
+ case INT64:
+ case FLOAT32:
+ case FLOAT64:
+ case BOOLEAN:
+ case STRING:
+ return value;
+ case BYTES:
+ if (value instanceof byte[]) {
+ return (byte[]) value;
+ } else if (value instanceof ByteBuffer) {
+ return ((ByteBuffer) value).array();
+ } else {
+ throw new ConnectException("Invalid type for bytes type: " + value.getClass());
+ }
+ case ARRAY: {
+ Collection collection = (Collection) value;
+ List list = new ArrayList();
+ for (Object elem : collection) {
+ Schema valueSchema = schema == null ? null : schema.getValueSchema();
+ Object fieldValue = convertToJson(valueSchema, elem);
+ list.add(fieldValue);
+ }
+ return list;
+ }
+ case MAP: {
+ Map<?, ?> map = (Map<?, ?>) value;
+ JSONArray resultArray = new JSONArray();
+ for (Map.Entry<?, ?> entry : map.entrySet()) {
+ Schema keySchema = schema == null ? null : schema.getKeySchema();
+ Schema valueSchema = schema == null ? null : schema.getValueSchema();
+ Object mapKey = convertToJson(keySchema, entry.getKey());
+ Object mapValue = convertToJson(valueSchema, entry.getValue());
+ JSONArray entryArray = new JSONArray();
+ entryArray.add(0, mapKey);
+ entryArray.add(1, mapValue);
+ resultArray.add(entryArray);
+ }
+ return resultArray;
+ }
+ case STRUCT: {
+ Struct struct = (Struct) value;
+ if (!struct.schema().equals(schema)) {
+ throw new ConnectException("Mismatching schema.");
+ }
+ JSONObject obj = new JSONObject(new LinkedHashMap());
+ for (Field field : struct.schema().getFields()) {
+ obj.put(field.getName(), convertToJson(field.getSchema(), struct.get(field)));
+ }
+ return obj;
+ }
+ }
+ throw new ConnectException("Couldn't convert " + value + " to JSON.");
+ } catch (ClassCastException e) {
+ String schemaTypeStr = (schema != null) ? schema.getFieldType().toString() : "unknown schema";
+ throw new ConnectException("Invalid type for " + schemaTypeStr + ": " + value.getClass());
+ }
+ }
+
+
+ /**
+ * convert json to schema if not empty
+ *
+ * @param jsonSchema
+ * @return
+ */
+ public Schema asConnectSchema(JSONObject jsonSchema) {
+ // schema null
+ if (jsonSchema == null) {
+ return null;
+ }
+ Schema cached = toConnectSchemaCache.get(jsonSchema);
+ if (cached != null) {
+ return cached;
+ }
+
+ String schemaType = String.valueOf(jsonSchema.get(JsonSchema.SCHEMA_TYPE_FIELD_NAME));
+ if (StringUtils.isEmpty(schemaType)) {
+ throw new ConnectException("Schema must contain 'type' field");
+ }
+ final SchemaBuilder builder;
+ switch (schemaType) {
+ case JsonSchema.BOOLEAN_TYPE_NAME:
+ builder = SchemaBuilder.bool();
+ break;
+ case JsonSchema.INT8_TYPE_NAME:
+ builder = SchemaBuilder.int8();
+ break;
+ case JsonSchema.INT16_TYPE_NAME:
+ builder = SchemaBuilder.int16();
+ break;
+ case JsonSchema.INT32_TYPE_NAME:
+ builder = SchemaBuilder.int32();
+ break;
+ case JsonSchema.INT64_TYPE_NAME:
+ builder = SchemaBuilder.int64();
+ break;
+ case JsonSchema.FLOAT_TYPE_NAME:
+ builder = SchemaBuilder.float32();
+ break;
+ case JsonSchema.DOUBLE_TYPE_NAME:
+ builder = SchemaBuilder.float64();
+ break;
+ case JsonSchema.BYTES_TYPE_NAME:
+ builder = SchemaBuilder.bytes();
+ break;
+ case JsonSchema.STRING_TYPE_NAME:
+ builder = SchemaBuilder.string();
+ break;
+ case JsonSchema.ARRAY_TYPE_NAME:
+ JSONObject elemSchema = (JSONObject) jsonSchema.get(JsonSchema.ARRAY_ITEMS_FIELD_NAME);
+ if (Objects.isNull(elemSchema)) {
+ throw new ConnectException("Array schema did not specify the element type");
+ }
+ builder = SchemaBuilder.array(asConnectSchema(elemSchema));
+ break;
+ case JsonSchema.MAP_TYPE_NAME:
+ JSONObject keySchema = (JSONObject) jsonSchema.get(JsonSchema.MAP_KEY_FIELD_NAME);
+ if (keySchema == null) {
+ throw new ConnectException("Map schema did not specify the key type");
+ }
+ JSONObject valueSchema = (JSONObject) jsonSchema.get(JsonSchema.MAP_VALUE_FIELD_NAME);
+ if (valueSchema == null) {
+ throw new ConnectException("Map schema did not specify the value type");
+ }
+ builder = SchemaBuilder.map(asConnectSchema(keySchema), asConnectSchema(valueSchema));
+ break;
+ case JsonSchema.STRUCT_TYPE_NAME:
+ builder = SchemaBuilder.struct();
+ List<JSONObject> fields = (List<JSONObject>) jsonSchema.get(JsonSchema.STRUCT_FIELDS_FIELD_NAME);
+ if (Objects.isNull(fields)) {
+ throw new ConnectException("Struct schema's \"fields\" argument is not an array.");
+ }
+ for (JSONObject field : fields) {
+ String jsonFieldName = field.getString(JsonSchema.STRUCT_FIELD_NAME_FIELD_NAME);
+ if (jsonFieldName == null) {
+ throw new ConnectException("Struct schema's field name not specified properly");
+ }
+ builder.field(jsonFieldName, asConnectSchema(field));
+ }
+ break;
+ default:
+ throw new ConnectException("Unknown schema type: " + schemaType);
+ }
+
+
+ // optional
+ Boolean isOptional = jsonSchema.getBoolean(JsonSchema.SCHEMA_OPTIONAL_FIELD_NAME);
+ if (isOptional != null && isOptional) {
+ builder.optional();
+ }
+
+ // schema name
+ String schemaName = jsonSchema.getString(JsonSchema.SCHEMA_NAME_FIELD_NAME);
+ builder.name(schemaName);
+
+ // schema version
+ Object version = jsonSchema.get(JsonSchema.SCHEMA_VERSION_FIELD_NAME);
+ if (version != null && version instanceof Integer) {
+ builder.version(Integer.parseInt(version.toString()));
+ }
+
+ // schema doc
+ String doc = jsonSchema.getString(JsonSchema.SCHEMA_DOC_FIELD_NAME);
+ if (StringUtils.isNotEmpty(doc)) {
+ builder.doc(doc);
+ }
+
+ // schema parameter
+ JSONObject schemaParams = (JSONObject) jsonSchema.get(JsonSchema.SCHEMA_PARAMETERS_FIELD_NAME);
+ if (schemaParams != null) {
+ Map<String, Object> paramsIt = schemaParams.getInnerMap();
+ paramsIt.forEach((k, v) -> {
+ builder.parameter(k, String.valueOf(v));
+ });
+ }
+
+ Object schemaDefaultNode = jsonSchema.get(JsonSchema.SCHEMA_DEFAULT_FIELD_NAME);
+ if (schemaDefaultNode != null) {
+ builder.defaultValue(convertToConnect(builder.build(), schemaDefaultNode));
+ }
+ Schema result = builder.build();
+ toConnectSchemaCache.put(jsonSchema, result);
+ return result;
+ }
+
+ /**
+ * convert to connect
+ *
+ * @param schema
+ * @param value
+ * @return
+ */
+ private Object convertToConnect(Schema schema, Object value) {
+ final FieldType schemaType;
+ if (schema != null) {
+ schemaType = schema.getFieldType();
+ if (value == null) {
+ if (schema.getDefaultValue() != null) {
+ return schema.getDefaultValue(); // any logical type conversions should already have been applied
+ }
+ if (schema.isOptional()) {
+ return null;
+ }
+ throw new ConnectException("Invalid null value for required " + schemaType + " field");
+ }
+ } else {
+ if (value == null) {
+ return null;
+ } else if (value instanceof String) {
+ schemaType = FieldType.STRING;
+ } else if (value instanceof Integer) {
+ schemaType = FieldType.INT32;
+ } else if (value instanceof Long) {
+ schemaType = FieldType.INT64;
+ } else if (value instanceof Float) {
+ schemaType = FieldType.FLOAT32;
+ } else if (value instanceof Double) {
+ schemaType = FieldType.FLOAT64;
+ } else if (value instanceof BigDecimal) {
+ schemaType = FieldType.FLOAT64;
+ } else if (value instanceof Boolean) {
+ schemaType = FieldType.BOOLEAN;
+ } else if (value instanceof List) {
+ schemaType = FieldType.ARRAY;
+ } else if (value instanceof Map) {
+ schemaType = FieldType.MAP;
+ } else {
+ schemaType = null;
+ }
+ }
+
+ final JsonToConnectTypeConverter typeConverter = TO_CONNECT_CONVERTERS.get(schemaType);
+ if (typeConverter == null) {
+ throw new ConnectException("Unknown schema type: " + schemaType);
+ }
+
+ if (schema != null && schema.getName() != null) {
+ LogicalTypeConverter logicalConverter = LOGICAL_CONVERTERS.get(schema.getName());
+ if (logicalConverter != null) {
+ return logicalConverter.toConnect(schema, value);
+ }
+ }
+
+ return typeConverter.convert(schema, value);
+ }
+
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/json/JsonConverterConfig.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/json/JsonConverterConfig.java
new file mode 100644
index 0000000..4099e92
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/json/JsonConverterConfig.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record.json;
+
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * Configuration options for {@link JsonConverter} instances.
+ */
+public class JsonConverterConfig {
+
+ public static final String SCHEMAS_ENABLE_CONFIG = "schemas.enable";
+ public static final boolean SCHEMAS_ENABLE_DEFAULT = true;
+ private static final String SCHEMAS_ENABLE_DOC = "Include schemas within each of the serialized values and keys.";
+ private static final String SCHEMAS_ENABLE_DISPLAY = "Enable Schemas";
+
+
+ public static final String SCHEMAS_CACHE_SIZE_CONFIG = "schemas.cache.size";
+ public static final int SCHEMAS_CACHE_SIZE_DEFAULT = 1000;
+ private static final String SCHEMAS_CACHE_SIZE_DOC = "The maximum number of schemas that can be cached in this converter instance.";
+ private static final String SCHEMAS_CACHE_SIZE_DISPLAY = "Schema Cache Size";
+
+
+ public static final String DECIMAL_FORMAT_CONFIG = "decimal.format";
+ public static final String DECIMAL_FORMAT_DEFAULT = DecimalFormat.BASE64.name();
+ private static final String DECIMAL_FORMAT_DOC = "Controls which format this converter will serialize decimals in."
+ + " This value is case insensitive and can be either 'BASE64' (default) or 'NUMERIC'";
+ private static final String DECIMAL_FORMAT_DISPLAY = "Decimal Format";
+
+ // cached config values
+ private final boolean schemasEnabled;
+ private final DecimalFormat decimalFormat;
+ private final int cacheSize;
+
+ public JsonConverterConfig(Map<String, ?> props) {
+ // schema.enabled
+ if (props.containsKey(SCHEMAS_ENABLE_CONFIG)) {
+ this.schemasEnabled = (Boolean) props.get(SCHEMAS_ENABLE_CONFIG);
+ } else {
+ this.schemasEnabled = SCHEMAS_ENABLE_DEFAULT;
+ }
+ // decimal format
+ if (props.containsKey(DECIMAL_FORMAT_CONFIG)) {
+ this.decimalFormat = DecimalFormat.valueOf(String.valueOf(props.get(DECIMAL_FORMAT_CONFIG)).toUpperCase(Locale.ROOT));
+ } else {
+ decimalFormat = DecimalFormat.valueOf(DECIMAL_FORMAT_DEFAULT);
+ }
+ this.cacheSize = props.containsKey(SCHEMAS_CACHE_SIZE_CONFIG) ? (Integer) props.get(SCHEMAS_CACHE_SIZE_CONFIG) : SCHEMAS_CACHE_SIZE_DEFAULT;
+
+ }
+
+ /**
+ * return cache size
+ *
+ * @return
+ */
+ public int cacheSize() {
+ return cacheSize;
+ }
+
+ /**
+ * Return whether schemas are enabled.
+ *
+ * @return true if enabled, or false otherwise
+ */
+ public boolean schemasEnabled() {
+ return schemasEnabled;
+ }
+
+ /**
+ * Get the serialization format for decimal types.
+ *
+ * @return the decimal serialization format
+ */
+ public DecimalFormat decimalFormat() {
+ return decimalFormat;
+ }
+
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/json/JsonSchema.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/json/JsonSchema.java
new file mode 100644
index 0000000..99cf1cd
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/converter/record/json/JsonSchema.java
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record.json;
+
+import com.alibaba.fastjson.JSONObject;
+
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * json schema
+ */
+public class JsonSchema {
+
+ public static final String ENVELOPE_SCHEMA_FIELD_NAME = "schema";
+ public static final String ENVELOPE_PAYLOAD_FIELD_NAME = "payload";
+ public static final String SCHEMA_TYPE_FIELD_NAME = "type";
+ public static final String SCHEMA_OPTIONAL_FIELD_NAME = "optional";
+ public static final String SCHEMA_NAME_FIELD_NAME = "name";
+ public static final String SCHEMA_VERSION_FIELD_NAME = "version";
+ public static final String SCHEMA_DOC_FIELD_NAME = "doc";
+ public static final String SCHEMA_PARAMETERS_FIELD_NAME = "parameters";
+ public static final String SCHEMA_DEFAULT_FIELD_NAME = "default";
+ public static final String ARRAY_ITEMS_FIELD_NAME = "items";
+ public static final String MAP_KEY_FIELD_NAME = "keys";
+ public static final String MAP_VALUE_FIELD_NAME = "values";
+ public static final String STRUCT_FIELDS_FIELD_NAME = "fields";
+ public static final String STRUCT_FIELD_NAME_FIELD_NAME = "field";
+ public static final String BOOLEAN_TYPE_NAME = "boolean";
+
+ public static JSONObject BOOLEAN_SCHEMA() {
+ return newJSONObject(SCHEMA_TYPE_FIELD_NAME, BOOLEAN_TYPE_NAME);
+ }
+
+ public static final String INT8_TYPE_NAME = "int8";
+
+ public static JSONObject INT8_SCHEMA() {
+ return newJSONObject(SCHEMA_TYPE_FIELD_NAME, INT8_TYPE_NAME);
+ }
+
+ public static final String INT16_TYPE_NAME = "int16";
+
+ public static JSONObject INT16_SCHEMA() {
+ return newJSONObject(SCHEMA_TYPE_FIELD_NAME, INT16_TYPE_NAME);
+ }
+
+ public static final String INT32_TYPE_NAME = "int32";
+
+ public static JSONObject INT32_SCHEMA() {
+ return newJSONObject(SCHEMA_TYPE_FIELD_NAME, INT32_TYPE_NAME);
+ }
+
+ public static final String INT64_TYPE_NAME = "int64";
+
+ public static JSONObject INT64_SCHEMA() {
+ return newJSONObject(SCHEMA_TYPE_FIELD_NAME, INT64_TYPE_NAME);
+ }
+
+ public static final String FLOAT_TYPE_NAME = "float";
+
+ public static JSONObject FLOAT_SCHEMA() {
+ return newJSONObject(SCHEMA_TYPE_FIELD_NAME, FLOAT_TYPE_NAME);
+ }
+
+ public static final String DOUBLE_TYPE_NAME = "double";
+
+ public static JSONObject DOUBLE_SCHEMA() {
+ return newJSONObject(SCHEMA_TYPE_FIELD_NAME, DOUBLE_TYPE_NAME);
+ }
+
+ public static final String BYTES_TYPE_NAME = "bytes";
+
+ public static JSONObject BYTES_SCHEMA() {
+ return newJSONObject(SCHEMA_TYPE_FIELD_NAME, BYTES_TYPE_NAME);
+ }
+
+ public static final String STRING_TYPE_NAME = "string";
+
+ public static JSONObject STRING_SCHEMA() {
+ return newJSONObject(SCHEMA_TYPE_FIELD_NAME, STRING_TYPE_NAME);
+ }
+
+ public static final String ARRAY_TYPE_NAME = "array";
+ public static final String MAP_TYPE_NAME = "map";
+ public static final String STRUCT_TYPE_NAME = "struct";
+
+
+ private static JSONObject newJSONObject(String key, Object value) {
+ JSONObject object = new JSONObject(new ConcurrentHashMap<>());
+ object.put(key, value);
+ return object;
+ }
+
+
+ public static JSONObject envelope(JSONObject schema, Object payload) {
+ JSONObject result = new JSONObject();
+ result.put(ENVELOPE_SCHEMA_FIELD_NAME, schema);
+ result.put(ENVELOPE_PAYLOAD_FIELD_NAME, payload);
+ return result;
+ }
+
+ static class Envelope {
+ public JSONObject schema;
+ public Object payload;
+
+ public Envelope(JSONObject schema, Object payload) {
+ this.schema = schema;
+ this.payload = payload;
+ }
+
+ public JSONObject toJsonNode() {
+ return envelope(schema, payload);
+ }
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/errors/ReporterManagerUtil.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/errors/ReporterManagerUtil.java
index 6c4e30a..2da9122 100644
--- a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/errors/ReporterManagerUtil.java
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/errors/ReporterManagerUtil.java
@@ -17,7 +17,7 @@
package org.apache.rocketmq.connect.runtime.errors;
-import io.openmessaging.connector.api.data.Converter;
+import io.openmessaging.connector.api.data.RecordConverter;
import org.apache.rocketmq.connect.runtime.common.ConnectKeyValue;
import org.apache.rocketmq.connect.runtime.config.ConnectConfig;
@@ -55,7 +55,7 @@ public class ReporterManagerUtil {
public static WorkerErrorRecordReporter createWorkerErrorRecordReporter(
ConnectKeyValue connConfig,
RetryWithToleranceOperator retryWithToleranceOperator,
- Converter converter) {
+ RecordConverter converter) {
DeadLetterQueueConfig deadLetterQueueConfig = new DeadLetterQueueConfig(connConfig);
if (deadLetterQueueConfig.enableErrantRecordReporter()) {
return new WorkerErrorRecordReporter(retryWithToleranceOperator, converter);
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/errors/WorkerErrorRecordReporter.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/errors/WorkerErrorRecordReporter.java
index 59533aa..d37ee7c 100644
--- a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/errors/WorkerErrorRecordReporter.java
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/errors/WorkerErrorRecordReporter.java
@@ -17,22 +17,25 @@
package org.apache.rocketmq.connect.runtime.errors;
+import com.alibaba.fastjson.JSON;
import io.openmessaging.connector.api.component.task.sink.ErrorRecordReporter;
import io.openmessaging.connector.api.component.task.sink.SinkTask;
import io.openmessaging.connector.api.data.ConnectRecord;
-import io.openmessaging.connector.api.data.Converter;
+import io.openmessaging.connector.api.data.RecordConverter;
+import io.openmessaging.connector.api.data.RecordPartition;
import org.apache.rocketmq.common.message.MessageExt;
+
/**
* worker error record reporter
*/
public class WorkerErrorRecordReporter implements ErrorRecordReporter {
private RetryWithToleranceOperator retryWithToleranceOperator;
- private Converter converter;
+ private RecordConverter converter;
public WorkerErrorRecordReporter(RetryWithToleranceOperator retryWithToleranceOperator,
- Converter converter) {
+ RecordConverter converter) {
this.retryWithToleranceOperator = retryWithToleranceOperator;
this.converter = converter;
}
@@ -46,9 +49,27 @@ public class WorkerErrorRecordReporter implements ErrorRecordReporter {
*/
@Override
public void report(ConnectRecord record, Throwable error) {
- byte[] value = converter.objectToByte(record.getData());
+ RecordPartition partition = record.getPosition().getPartition();
+ String topic = partition.getPartition().containsKey("topic") ? String.valueOf(partition.getPartition().get("topic")) : null;
+ Integer queueId = partition.getPartition().containsKey("queueId") ? (Integer) partition.getPartition().get("queueId") : null;
+ Long queueOffset = partition.getPartition().containsKey("queueOffset") ? (Long) partition.getPartition().get("queueOffset") : null;
+ String brokerName = partition.getPartition().containsKey("brokerName") ? String.valueOf(partition.getPartition().get("topic")) : null;
+
MessageExt consumerRecord = new MessageExt();
- consumerRecord.setBody(value);
+ if (converter != null && converter instanceof RecordConverter){
+ byte[] value = converter.fromConnectData(topic, record.getSchema(), record.getData());
+ consumerRecord.setBody(value);
+ consumerRecord.setBrokerName(brokerName);
+ consumerRecord.setQueueId(queueId);
+ consumerRecord.setQueueOffset(queueOffset);
+ }else {
+ byte[] messageBody = JSON.toJSONString(record).getBytes();
+ consumerRecord.setBody(messageBody);
+ }
+ // add extensions
+ record.getExtensions().keySet().forEach(key->{
+ consumerRecord.putUserProperty(key, record.getExtensions().getString(key));
+ });
retryWithToleranceOperator.executeFailed(ErrorReporter.Stage.TASK_PUT, SinkTask.class, consumerRecord, error);
}
}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ByteArrayDeserializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ByteArrayDeserializer.java
new file mode 100644
index 0000000..64da3be
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ByteArrayDeserializer.java
@@ -0,0 +1,25 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+public class ByteArrayDeserializer implements Deserializer<byte[]> {
+
+ @Override
+ public byte[] deserialize(String topic, byte[] data) {
+ return data;
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ByteArraySerializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ByteArraySerializer.java
new file mode 100644
index 0000000..f8a83e8
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ByteArraySerializer.java
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+public class ByteArraySerializer implements Serializer<byte[]> {
+ @Override
+ public byte[] serialize(String topic, byte[] data) {
+ return data;
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ByteBufferDeserializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ByteBufferDeserializer.java
new file mode 100644
index 0000000..fdca5b1
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ByteBufferDeserializer.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import java.nio.ByteBuffer;
+
+public class ByteBufferDeserializer implements Deserializer<ByteBuffer> {
+ @Override
+ public ByteBuffer deserialize(String topic, byte[] data) {
+ if (data == null) {
+ return null;
+ }
+
+ return ByteBuffer.wrap(data);
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ByteBufferSerializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ByteBufferSerializer.java
new file mode 100644
index 0000000..a53a44e
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ByteBufferSerializer.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import java.nio.ByteBuffer;
+
+public class ByteBufferSerializer implements Serializer<ByteBuffer> {
+ @Override
+ public byte[] serialize(String topic, ByteBuffer data) {
+ if (data == null) {
+ return null;
+ }
+
+ data.rewind();
+ if (data.hasArray()) {
+ byte[] arr = data.array();
+ if (data.arrayOffset() == 0 && arr.length == data.remaining()) {
+ return arr;
+ }
+ }
+
+ byte[] ret = new byte[data.remaining()];
+ data.get(ret, 0, ret.length);
+ data.rewind();
+ return ret;
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/Deserializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/Deserializer.java
new file mode 100644
index 0000000..2db9be0
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/Deserializer.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import io.openmessaging.KeyValue;
+
+import java.io.Closeable;
+import java.util.Map;
+
+/**
+ * An interface for converting bytes to objects.
+ *
+ * @param <T> Type to be deserialized into.
+ */
+public interface Deserializer<T> extends Closeable {
+
+ /**
+ * Configure this class.
+ * @param configs configs in key/value pairs
+ */
+ default void configure(Map<String, ?> configs) {
+ // intentionally left blank
+ }
+
+ /**
+ * Deserialize a record value from a byte array into a value or object.
+ * @param topic topic associated with the data
+ * @param data serialized bytes; may be null; implementations are recommended to handle null by returning a value or null rather than throwing an exception.
+ * @return deserialized typed data; may be null
+ */
+ T deserialize(String topic, byte[] data);
+
+ /**
+ * Deserialize a record value from a byte array into a value or object.
+ */
+ default T deserialize(String topic, KeyValue extensions, byte[] data) {
+ return deserialize(topic, data);
+ }
+
+ /**
+ * Close this deserializer.
+ * <p>
+ * This method must be idempotent as it may be called multiple times.
+ */
+ @Override
+ default void close() {
+ // intentionally left blank
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/DoubleDeserializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/DoubleDeserializer.java
new file mode 100644
index 0000000..5cc9be5
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/DoubleDeserializer.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import org.apache.commons.lang3.SerializationException;
+
+public class DoubleDeserializer implements Deserializer<Double> {
+
+ @Override
+ public Double deserialize(String topic, byte[] data) {
+ if (data == null)
+ return null;
+ if (data.length != 8) {
+ throw new SerializationException("Size of data received by Deserializer is not 8");
+ }
+
+ long value = 0;
+ for (byte b : data) {
+ value <<= 8;
+ value |= b & 0xFF;
+ }
+ return Double.longBitsToDouble(value);
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/DoubleSerializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/DoubleSerializer.java
new file mode 100644
index 0000000..696bbae
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/DoubleSerializer.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+public class DoubleSerializer implements Serializer<Double> {
+ @Override
+ public byte[] serialize(String topic, Double data) {
+ if (data == null) {
+ return null;
+ }
+
+ long bits = Double.doubleToLongBits(data);
+ return new byte[] {
+ (byte) (bits >>> 56),
+ (byte) (bits >>> 48),
+ (byte) (bits >>> 40),
+ (byte) (bits >>> 32),
+ (byte) (bits >>> 24),
+ (byte) (bits >>> 16),
+ (byte) (bits >>> 8),
+ (byte) bits
+ };
+ }
+}
\ No newline at end of file
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/FloatDeserializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/FloatDeserializer.java
new file mode 100644
index 0000000..fd4dad0
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/FloatDeserializer.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import org.apache.commons.lang3.SerializationException;
+
+public class FloatDeserializer implements Deserializer<Float> {
+ @Override
+ public Float deserialize(final String topic, final byte[] data) {
+ if (data == null) {
+ return null;
+ }
+ if (data.length != 4) {
+ throw new SerializationException("Size of data received by Deserializer is not 4");
+ }
+
+ int value = 0;
+ for (byte b : data) {
+ value <<= 8;
+ value |= b & 0xFF;
+ }
+ return Float.intBitsToFloat(value);
+ }
+}
\ No newline at end of file
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/FloatSerializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/FloatSerializer.java
new file mode 100644
index 0000000..f511ee0
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/FloatSerializer.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+public class FloatSerializer implements Serializer<Float> {
+ @Override
+ public byte[] serialize(final String topic, final Float data) {
+ if (data == null) {
+ return null;
+ }
+
+ long bits = Float.floatToRawIntBits(data);
+ return new byte[] {
+ (byte) (bits >>> 24),
+ (byte) (bits >>> 16),
+ (byte) (bits >>> 8),
+ (byte) bits
+ };
+ }
+}
\ No newline at end of file
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/IntegerDeserializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/IntegerDeserializer.java
new file mode 100644
index 0000000..8213705
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/IntegerDeserializer.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import org.apache.commons.lang3.SerializationException;
+
+public class IntegerDeserializer implements Deserializer<Integer> {
+ @Override
+ public Integer deserialize(String topic, byte[] data) {
+ if (data == null) {
+ return null;
+ }
+ if (data.length != 4) {
+ throw new SerializationException("Size of data received by IntegerDeserializer is not 4");
+ }
+
+ int value = 0;
+ for (byte b : data) {
+ value <<= 8;
+ value |= b & 0xFF;
+ }
+ return value;
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/IntegerSerializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/IntegerSerializer.java
new file mode 100644
index 0000000..3a3838a
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/IntegerSerializer.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+public class IntegerSerializer implements Serializer<Integer> {
+ @Override
+ public byte[] serialize(String topic, Integer data) {
+ if (data == null) {
+ return null;
+ }
+
+ return new byte[] {
+ (byte) (data >>> 24),
+ (byte) (data >>> 16),
+ (byte) (data >>> 8),
+ data.byteValue()
+ };
+ }
+}
\ No newline at end of file
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/JsonDeserializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/JsonDeserializer.java
new file mode 100644
index 0000000..283c89d
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/JsonDeserializer.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import com.alibaba.fastjson.JSON;
+import io.openmessaging.connector.api.errors.ConnectException;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Objects;
+
+/**
+ * json deserializer
+ */
+public class JsonDeserializer implements Deserializer<Object> {
+
+ @Override
+ public Object deserialize(String topic, byte[] bytes) {
+ if (Objects.isNull(bytes)) {
+ return null;
+ }
+ Object data;
+ try {
+ data = JSON.parse(new String(bytes, StandardCharsets.UTF_8));
+ } catch (Exception e) {
+ throw new ConnectException(e);
+ }
+ return data;
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/JsonSerializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/JsonSerializer.java
new file mode 100644
index 0000000..1876082
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/JsonSerializer.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.serializer.SerializerFeature;
+import io.openmessaging.connector.api.errors.ConnectException;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Objects;
+
+/**
+ * json serializer
+ */
+public class JsonSerializer implements Serializer<Object> {
+
+
+ /**
+ * Convert {@code data} into a byte array.
+ *
+ * @param topic topic associated with data
+ * @param data typed data
+ * @return serialized bytes
+ */
+ @Override
+ public byte[] serialize(String topic, Object data) {
+ if (Objects.isNull(data)) {
+ return null;
+ }
+ try {
+ return JSON.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue).getBytes(StandardCharsets.UTF_8);
+ } catch (Exception e) {
+ throw new ConnectException("Error serializing JSON message", e);
+ }
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/LongDeserializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/LongDeserializer.java
new file mode 100644
index 0000000..4a0b0e6
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/LongDeserializer.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import org.apache.commons.lang3.SerializationException;
+
+public class LongDeserializer implements Deserializer<Long> {
+ @Override
+ public Long deserialize(String topic, byte[] data) {
+ if (data == null) {
+ return null;
+ }
+ if (data.length != 8) {
+ throw new SerializationException("Size of data received by LongDeserializer is not 8");
+ }
+
+ long value = 0;
+ for (byte b : data) {
+ value <<= 8;
+ value |= b & 0xFF;
+ }
+ return value;
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/LongSerializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/LongSerializer.java
new file mode 100644
index 0000000..f09fcc4
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/LongSerializer.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+public class LongSerializer implements Serializer<Long> {
+ @Override
+ public byte[] serialize(String topic, Long data) {
+ if (data == null) {
+ return null;
+ }
+
+ return new byte[] {
+ (byte) (data >>> 56),
+ (byte) (data >>> 48),
+ (byte) (data >>> 40),
+ (byte) (data >>> 32),
+ (byte) (data >>> 24),
+ (byte) (data >>> 16),
+ (byte) (data >>> 8),
+ data.byteValue()
+ };
+ }
+}
\ No newline at end of file
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/Serializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/Serializer.java
new file mode 100644
index 0000000..bd18cab
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/Serializer.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import io.openmessaging.KeyValue;
+
+import java.io.Closeable;
+import java.util.Map;
+
+/**
+ * An interface for converting objects to bytes.
+ */
+public interface Serializer<T> extends Closeable {
+
+ /**
+ * Configure this class.
+ * @param configs configs in key/value pairs
+ */
+ default void configure(Map<String, ?> configs) {
+ // intentionally left blank
+ }
+
+ /**
+ * Convert {@code data} into a byte array.
+ *
+ * @param topic topic associated with data
+ * @param data typed data
+ * @return serialized bytes
+ */
+ byte[] serialize(String topic, T data);
+
+ /**
+ * Convert data into a byte array.
+ * @return serialized bytes
+ */
+ default byte[] serialize(String topic, KeyValue extensions, T data) {
+ return serialize(topic, data);
+ }
+
+ /**
+ * Close this serializer.
+ */
+ @Override
+ default void close() {
+ // intentionally left blank
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ShortDeserializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ShortDeserializer.java
new file mode 100644
index 0000000..0d82046
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ShortDeserializer.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import org.apache.commons.lang3.SerializationException;
+
+public class ShortDeserializer implements Deserializer<Short> {
+
+ @Override
+ public Short deserialize(String topic, byte[] data) {
+ if (data == null) {
+ return null;
+ }
+ if (data.length != 2) {
+ throw new SerializationException("Size of data received by ShortDeserializer is not 2");
+ }
+
+ short value = 0;
+ for (byte b : data) {
+ value <<= 8;
+ value |= b & 0xFF;
+ }
+ return value;
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ShortSerializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ShortSerializer.java
new file mode 100644
index 0000000..c18e005
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/ShortSerializer.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+public class ShortSerializer implements Serializer<Short> {
+ @Override
+ public byte[] serialize(String topic, Short data) {
+ if (data == null) {
+ return null;
+ }
+
+ return new byte[] {
+ (byte) (data >>> 8),
+ data.byteValue()
+ };
+ }
+}
\ No newline at end of file
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/StringDeserializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/StringDeserializer.java
new file mode 100644
index 0000000..60a75b7
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/StringDeserializer.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Map;
+
+/**
+ * String encoding defaults to UTF8 and can be customized by setting the property key.deserializer.encoding,
+ * value.deserializer.encoding or deserializer.encoding. The first two take precedence over the last.
+ */
+public class StringDeserializer implements Deserializer<String> {
+ private String encoding = "UTF8";
+
+ @Override
+ public void configure(Map<String, ?> configs) {
+ Object encodingValue = configs.get("deserializer.encoding");
+ if (encodingValue instanceof String) {
+ encoding = (String) encodingValue;
+ }
+ }
+
+ @Override
+ public String deserialize(String topic, byte[] data) {
+ try {
+ if (data == null) {
+ return null;
+ } else {
+ return new String(data, encoding);
+ }
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException("Error when deserializing byte[] to string due to unsupported encoding " + encoding);
+ }
+ }
+}
diff --git a/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/StringSerializer.java b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/StringSerializer.java
new file mode 100644
index 0000000..6d941ba
--- /dev/null
+++ b/rocketmq-connect-runtime/src/main/java/org/apache/rocketmq/connect/runtime/serialization/StringSerializer.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.serialization;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Map;
+
+/**
+ * string serializer
+ */
+public class StringSerializer implements Serializer<String> {
+ private String encoding = "UTF8";
+
+ @Override
+ public void configure(Map<String, ?> configs) {
+ String propertyName = "serializer.encoding";
+ if (configs.containsKey(propertyName)) {
+ Object encodingValue = configs.get(propertyName);
+ if (encodingValue instanceof String) {
+ encoding = (String) encodingValue;
+ }
+ }
+ }
+
+ @Override
+ public byte[] serialize(String topic, String data) {
+ try {
+ if (data == null) {
+ return null;
+ } else {
+ return data.getBytes(encoding);
+ }
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException("Error when serializing string to byte[] due to unsupported encoding " + encoding);
+ }
+ }
+}
\ No newline at end of file
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/common/FastJsonTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/common/FastJsonTest.java
new file mode 100644
index 0000000..b2d875a
--- /dev/null
+++ b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/common/FastJsonTest.java
@@ -0,0 +1,30 @@
+package org.apache.rocketmq.connect.runtime.common;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.alibaba.fastjson.util.TypeUtils;
+
+import java.nio.charset.StandardCharsets;
+
+public class FastJsonTest {
+ static class TestByte{
+ private Object bytes= "123".getBytes(StandardCharsets.UTF_8);
+
+ public Object getBytes() {
+ return bytes;
+ }
+
+ public void setBytes(Object bytes) {
+ this.bytes = bytes;
+ }
+ }
+
+ public static void main(String[] args) {
+ TestByte testByte = new TestByte();
+ byte[] originalJson=JSON.toJSONBytes(testByte);
+ JSONObject str=(JSONObject)JSON.parse(originalJson);
+ byte[] byte1=TypeUtils.castToBytes(str.get("bytes").toString());
+ System.out.println(new java.lang.String(byte1,StandardCharsets.UTF_8));
+ }
+
+}
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerTest.java
index 0c98f12..7931eac 100644
--- a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerTest.java
+++ b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/connectorwrapper/WorkerTest.java
@@ -38,6 +38,7 @@ import org.apache.rocketmq.connect.runtime.connectorwrapper.testimpl.TestConnect
import org.apache.rocketmq.connect.runtime.connectorwrapper.testimpl.TestConverter;
import org.apache.rocketmq.connect.runtime.connectorwrapper.testimpl.TestPositionManageServiceImpl;
import org.apache.rocketmq.connect.runtime.connectorwrapper.testimpl.TestSourceTask;
+import org.apache.rocketmq.connect.runtime.converter.record.json.JsonConverter;
import org.apache.rocketmq.connect.runtime.errors.ReporterManagerUtil;
import org.apache.rocketmq.connect.runtime.errors.RetryWithToleranceOperator;
import org.apache.rocketmq.connect.runtime.service.ConfigManagementService;
@@ -121,7 +122,7 @@ public class WorkerTest {
new TestSourceTask(),
connectKeyValue,
new TestPositionManageServiceImpl(),
- new TestConverter(),
+ new JsonConverter(),
producer,
new AtomicReference(WorkerState.STARTED),
connectStatsManager, connectStatsService,
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/JsonConverterTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/JsonConverterTest.java
deleted file mode 100644
index 5117840..0000000
--- a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/JsonConverterTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.rocketmq.connect.runtime.converter;
-
-import java.util.HashMap;
-import java.util.Map;
-import org.junit.Test;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class JsonConverterTest {
-
- @Test
- public void testJsonConverter() {
- Map<String, String> data = new HashMap<>();
- data.put("test_key", "test_value");
- JsonConverter jc = new JsonConverter();
- byte[] o2b = jc.objectToByte(data);
- Map<String, String> b2o = (Map<String, String>) jc.byteToObject(o2b);
- assertThat(b2o.size()).isEqualTo(1);
- assertThat(b2o.keySet().size()).isEqualTo(1);
- assertThat(b2o.values().size()).isEqualTo(1);
- for (String key : b2o.keySet()) {
- assertThat(new String(key)).isEqualTo("test_key");
- assertThat(new String(b2o.get(key))).isEqualTo("test_value");
- }
- }
-}
\ No newline at end of file
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/AbstractRecordConverterTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/AbstractRecordConverterTest.java
new file mode 100644
index 0000000..ccf8cfe
--- /dev/null
+++ b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/AbstractRecordConverterTest.java
@@ -0,0 +1,12 @@
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.RecordConverter;
+
+/**
+ * record converter test
+ */
+public class AbstractRecordConverterTest {
+ protected RecordConverter recordConverter;
+ protected final String TEST_TOPIC= "test_topic";
+
+}
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/DoubleConverterTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/DoubleConverterTest.java
new file mode 100644
index 0000000..99f3be1
--- /dev/null
+++ b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/DoubleConverterTest.java
@@ -0,0 +1,25 @@
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.SchemaAndValue;
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class DoubleConverterTest extends AbstractRecordConverterTest {
+
+
+ @Before
+ public void before(){
+ this.recordConverter = new DoubleConverter();
+ }
+
+
+ @Test
+ public void testDoubleConverter() {
+ Double float64 = 32.00;
+ byte[] bytes = recordConverter.fromConnectData(TEST_TOPIC, SchemaBuilder.float64().build(), float64);
+ SchemaAndValue schemaAndValue = recordConverter.toConnectData(TEST_TOPIC, bytes);
+ Assert.assertEquals(schemaAndValue.value(), float64);
+ }
+}
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/IntegerConverterTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/IntegerConverterTest.java
new file mode 100644
index 0000000..971150f
--- /dev/null
+++ b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/IntegerConverterTest.java
@@ -0,0 +1,27 @@
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.SchemaAndValue;
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class IntegerConverterTest extends AbstractRecordConverterTest {
+
+
+ @Before
+ public void before(){
+ this.recordConverter = new IntegerConverter();
+ }
+
+
+ @Test
+ public void testIntegerConverter() {
+ Integer int32 = 32;
+ byte[] bytes = recordConverter.fromConnectData(TEST_TOPIC, SchemaBuilder.int32().build(), int32);
+ SchemaAndValue schemaAndValue = recordConverter.toConnectData(TEST_TOPIC, bytes);
+ Assert.assertEquals(schemaAndValue.value(), int32);
+ }
+}
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/JsonConverterConfigTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/JsonConverterConfigTest.java
new file mode 100644
index 0000000..8cdf3f3
--- /dev/null
+++ b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/JsonConverterConfigTest.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import org.apache.rocketmq.connect.runtime.converter.record.json.DecimalFormat;
+import org.apache.rocketmq.connect.runtime.converter.record.json.JsonConverterConfig;
+import org.junit.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+
+public class JsonConverterConfigTest {
+
+ @Test
+ public void shouldBeCaseInsensitiveForDecimalFormatConfig() {
+ final Map<String, Object> configValues = new HashMap<>();
+ configValues.put(JsonConverterConfig.DECIMAL_FORMAT_CONFIG, "NuMeRiC");
+ final JsonConverterConfig config = new JsonConverterConfig(configValues);
+ assertEquals(config.decimalFormat(), DecimalFormat.NUMERIC);
+ }
+
+}
\ No newline at end of file
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/JsonConverterTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/JsonConverterTest.java
new file mode 100644
index 0000000..03b3255
--- /dev/null
+++ b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/JsonConverterTest.java
@@ -0,0 +1,881 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.alibaba.fastjson.util.TypeUtils;
+import com.google.common.collect.Maps;
+import io.openmessaging.connector.api.data.Schema;
+import io.openmessaging.connector.api.data.SchemaAndValue;
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import io.openmessaging.connector.api.data.Struct;
+import io.openmessaging.connector.api.data.logical.Date;
+import io.openmessaging.connector.api.data.logical.Decimal;
+import io.openmessaging.connector.api.data.logical.Time;
+import io.openmessaging.connector.api.data.logical.Timestamp;
+import io.openmessaging.connector.api.errors.ConnectException;
+import org.apache.rocketmq.connect.runtime.converter.record.json.DecimalFormat;
+import org.apache.rocketmq.connect.runtime.converter.record.json.JsonConverterConfig;
+import org.apache.rocketmq.connect.runtime.converter.record.json.JsonSchema;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.UnsupportedEncodingException;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.TimeZone;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.fail;
+import org.apache.rocketmq.connect.runtime.converter.record.json.JsonConverter;
+
+public class JsonConverterTest {
+ private static final String TOPIC = "topic";
+ private final JSONObject objectMapper = new JSONObject();
+ private final JsonConverter converter = new JsonConverter();
+
+ @Before
+ public void setUp() {
+ Map<String, Object> config = Maps.newConcurrentMap();
+ config.put(JsonConverterConfig.SCHEMAS_ENABLE_CONFIG, true);
+ converter.configure(config);
+ }
+
+ // Schema metadata
+
+ @Test
+ public void testConnectSchemaMetadataTranslation() {
+ // this validates the non-type fields are translated and handled properly
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"boolean\",\"optional\": \"true\" }, \"payload\": true }".getBytes());
+ SchemaAndValue newSchemaAndValue = new SchemaAndValue(SchemaBuilder.bool().build(), true);
+ assertEquals(newSchemaAndValue, schemaAndValue);
+
+ SchemaAndValue schemaAndValue01 = converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"boolean\", \"optional\": true }, \"payload\": null }".getBytes());
+ SchemaAndValue newSchemaAndValue01 = new SchemaAndValue(SchemaBuilder.bool().optional().build(), null);
+ assertEquals(schemaAndValue01, newSchemaAndValue01);
+
+ SchemaAndValue schemaAndValue02 = converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"boolean\", \"optional\": true, \"default\": true}, \"payload\": true }".getBytes());
+ SchemaAndValue newSchemaAndValue02 = new SchemaAndValue(SchemaBuilder.bool().defaultValue(true).build(), true);
+ assertEquals(schemaAndValue02, newSchemaAndValue02);
+
+
+ SchemaAndValue schemaAndValue03 = converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"boolean\", \"optional\": true, \"name\": \"bool\", \"version\": 2, \"doc\": \"the documentation\", \"parameters\": { \"foo\": \"bar\" }}, \"payload\": true }".getBytes());
+ SchemaAndValue newSchemaAndValue03 = new SchemaAndValue(SchemaBuilder.bool().name("bool").version(2).doc("the documentation").parameter("foo", "bar").build(), true);
+
+ assertEquals(newSchemaAndValue03, schemaAndValue03);
+ }
+
+ // Schema types
+
+ @Test
+ public void booleanToConnect() {
+ assertEquals(
+ new SchemaAndValue(SchemaBuilder.bool().build(), true),
+ converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"boolean\",\"optional\": true }, \"payload\": true }".getBytes())
+ );
+ assertEquals(
+ new SchemaAndValue(SchemaBuilder.bool().build(), false),
+ converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"boolean\" ,\"optional\": false}, \"payload\": false }".getBytes())
+ );
+ }
+
+ @Test
+ public void byteToConnect() {
+ assertEquals(
+ new SchemaAndValue(SchemaBuilder.int8().build(), (byte) 12),
+ converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"int8\",\"optional\": true }, \"payload\": 12 }".getBytes())
+ );
+ }
+
+ @Test
+ public void shortToConnect() {
+ assertEquals(
+ new SchemaAndValue(SchemaBuilder.int16().build(), (short) 12),
+ converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"int16\" ,\"optional\": true}, \"payload\": 12 }".getBytes())
+ );
+ }
+
+ @Test
+ public void intToConnect() {
+ assertEquals(
+ new SchemaAndValue(SchemaBuilder.int32().build(), 12),
+ converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"int32\" ,\"optional\": true}, \"payload\": 12 }".getBytes())
+ );
+ }
+
+ @Test
+ public void longToConnect() {
+ assertEquals(
+ new SchemaAndValue(SchemaBuilder.int64().build(), 12L),
+ converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"int64\" ,\"optional\": true }, \"payload\": 12 }".getBytes())
+ );
+ assertEquals(
+ new SchemaAndValue(SchemaBuilder.int64().build(), 4398046511104L),
+ converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"int64\" ,\"optional\": true }, \"payload\": 4398046511104 }".getBytes())
+ );
+ }
+
+ @Test
+ public void floatToConnect() {
+ assertEquals(
+ new SchemaAndValue(SchemaBuilder.float32().build(), 12.34f),
+ converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"float\" ,\"optional\": true }, \"payload\": 12.34 }".getBytes())
+ );
+ }
+
+ @Test
+ public void doubleToConnect() {
+ assertEquals(
+ new SchemaAndValue(SchemaBuilder.float64().build(), 12.34),
+ converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"double\",\"optional\": true }, \"payload\": 12.34 }".getBytes())
+ );
+ }
+
+
+ @Test
+ public void bytesToConnect() throws UnsupportedEncodingException {
+ ByteBuffer reference = ByteBuffer.wrap("test-string".getBytes("UTF-8"));
+ String msg = "{ \"schema\": { \"type\": \"bytes\",\"optional\": true }, \"payload\": \"dGVzdC1zdHJpbmc=\" }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ ByteBuffer converted = ByteBuffer.wrap((byte[]) schemaAndValue.value());
+ assertEquals(reference, converted);
+ }
+
+ @Test
+ public void stringToConnect() {
+ assertEquals(
+ new SchemaAndValue(SchemaBuilder.string().build(), "foo-bar-baz"),
+ converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"string\",\"optional\": true }, \"payload\": \"foo-bar-baz\" }".getBytes()
+ )
+ );
+ }
+
+ @Test
+ public void arrayToConnect() {
+ byte[] arrayJson = "{ \"schema\": { \"type\": \"array\", \"items\": { \"type\" : \"int32\",\"optional\": true } ,\"optional\": true}, \"payload\": [1, 2, 3] }".getBytes();
+ assertEquals(
+ new SchemaAndValue(
+ SchemaBuilder.array(SchemaBuilder.int32().build()).build(),
+ Arrays.asList(1, 2, 3)
+ ),
+ converter.toConnectData(TOPIC, arrayJson)
+ );
+ }
+
+ @Test
+ public void mapToConnectStringKeys() {
+ byte[] mapJson = "{ \"schema\": { \"type\": \"map\", \"keys\": { \"type\" : \"string\",\"optional\": true}, \"values\": { \"type\" : \"int32\" ,\"optional\": true } ,\"optional\": true}, \"payload\": { \"key1\": 12, \"key2\": 15} }".getBytes();
+ Map<String, Integer> expected = new HashMap<>();
+ expected.put("key1", 12);
+ expected.put("key2", 15);
+ assertEquals(
+ new SchemaAndValue(
+ SchemaBuilder.map(SchemaBuilder.string().build(), SchemaBuilder.int32().build()).build(), expected
+ ),
+ converter.toConnectData(TOPIC, mapJson)
+ );
+ }
+
+ @Test
+ public void mapToConnectNonStringKeys() {
+ byte[] mapJson = "{ \"schema\": { \"type\": \"map\", \"keys\": { \"type\" : \"int32\" }, \"values\": { \"type\" : \"int32\" } }, \"payload\": [ [1, 12], [2, 15] ] }".getBytes();
+ Map<Integer, Integer> expected = new HashMap<>();
+ expected.put(1, 12);
+ expected.put(2, 15);
+ assertEquals(
+ new SchemaAndValue(
+ SchemaBuilder.map(SchemaBuilder.int32().build(), SchemaBuilder.int32().build()).build(),
+ expected
+ ),
+ converter.toConnectData(TOPIC, mapJson)
+ );
+ }
+
+ @Test
+ public void structToConnect() {
+ byte[] structJson = "{ \"schema\": { \"type\": \"struct\", \"fields\": [{ \"field\": \"field1\", \"type\": \"boolean\" }, { \"field\": \"field2\", \"type\": \"string\" }] }, \"payload\": { \"field1\": true, \"field2\": \"string\" } }".getBytes();
+ Schema expectedSchema =
+ SchemaBuilder
+ .struct()
+ .field("field1", SchemaBuilder.bool().build())
+ .field("field2", SchemaBuilder.string().build()).build();
+ Struct expected = new Struct(expectedSchema)
+ .put("field1", true)
+ .put("field2", "string");
+ SchemaAndValue converted = converter.toConnectData(TOPIC, structJson);
+ assertEquals(new SchemaAndValue(expectedSchema, expected).toString(), converted.toString());
+ }
+
+ @Test
+ public void structWithOptionalFieldToConnect() {
+ byte[] structJson = "{ \"schema\": { \"type\": \"struct\", \"fields\": [{ \"field\":\"optional\", \"type\": \"string\", \"optional\": true }, { \"field\": \"required\", \"type\": \"string\" }] }, \"payload\": { \"required\": \"required\" } }".getBytes();
+ Schema expectedSchema = SchemaBuilder
+ .struct()
+ .field("optional", SchemaBuilder.string().build())
+ .field("required", SchemaBuilder.string().required().build()).build();
+ Struct expected = new Struct(expectedSchema).put("required", "required");
+ SchemaAndValue converted = converter.toConnectData(TOPIC, structJson);
+ assertEquals(
+ new SchemaAndValue(expectedSchema, expected),
+ converted
+ );
+ }
+
+ @Test
+ public void nullToConnect() {
+ // When schemas are enabled, trying to decode a tombstone should be an empty envelope
+ // the behavior is the same as when the json is "{ "schema": null, "payload": null }"
+ // to keep compatibility with the record
+ SchemaAndValue converted = converter.toConnectData(TOPIC, null);
+ assertEquals(SchemaAndValue.NULL, converted);
+ }
+
+ @Test
+ public void nullSchemaPrimitiveToConnect() {
+ SchemaAndValue converted = converter.toConnectData(TOPIC, "{ \"schema\": null, \"payload\": null }".getBytes());
+ assertEquals(SchemaAndValue.NULL, converted);
+
+ converted = converter.toConnectData(TOPIC, "{ \"schema\": null, \"payload\": true }".getBytes());
+ assertEquals(new SchemaAndValue(null, true), converted);
+
+ // Integers: Connect has more data types, and JSON unfortunately mixes all number types. We try to preserve
+ // info as best we can, so we always use the largest integer and floating point numbers we can and have Jackson
+ // determine if it's an integer or not
+ converted = converter.toConnectData(TOPIC, "{ \"schema\": null, \"payload\": 12 }".getBytes());
+ assertEquals(new SchemaAndValue(null, 12), converted);
+
+ converted = converter.toConnectData(TOPIC, "{ \"schema\": null, \"payload\": 12.24 }".getBytes());
+ assertEquals(new SchemaAndValue(null, 12.24), converted);
+
+ converted = converter.toConnectData(TOPIC, "{ \"schema\": null, \"payload\": \"a string\" }".getBytes());
+ assertEquals(new SchemaAndValue(null, "a string"), converted);
+
+ converted = converter.toConnectData(TOPIC, "{ \"schema\": null, \"payload\": [1, \"2\", 3] }".getBytes());
+ assertEquals(new SchemaAndValue(null, Arrays.asList(1L, "2", 3L)).toString(), converted.toString());
+
+ converted = converter.toConnectData(TOPIC, "{ \"schema\": null, \"payload\": { \"field1\": 1, \"field2\": 2} }".getBytes());
+ Map<String, Long> obj = new HashMap<>();
+ obj.put("field1", 1L);
+ obj.put("field2", 2L);
+ assertEquals(new SchemaAndValue(null, obj).toString(), converted.toString());
+ }
+
+ @Test
+ public void decimalToConnect() {
+ Schema schema = Decimal.schema(2);
+ BigDecimal reference = new BigDecimal(new BigInteger("156"), 2);
+ String msg = "{ \"schema\": { \"type\": \"bytes\", \"name\": \"io.openmessaging.connector.api.data.logical.Decimal\", \"version\": 1, \"parameters\": { \"scale\": \"2\" } }, \"payload\": \"1.56\" }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ BigDecimal converted = (BigDecimal) schemaAndValue.value();
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, converted);
+ }
+
+ @Test
+ public void decimalToConnectOptional() {
+ Schema schema = Decimal.builder(2).optional().build();
+ String msg = "{ \"schema\": { \"type\": \"bytes\", \"name\": \"io.openmessaging.connector.api.data.logical.Decimal\", \"version\": 1, \"optional\": true, \"parameters\": { \"scale\": \"2\" } }, \"payload\": null }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertNull(schemaAndValue.value());
+ }
+
+ @Test
+ public void decimalToConnectWithDefaultValue() {
+ BigDecimal reference = new BigDecimal(new BigInteger("156"), 2);
+ Schema schema = Decimal.builder(2).defaultValue(reference).build();
+ String msg = "{ \"schema\": { \"type\": \"bytes\", \"name\": \"io.openmessaging.connector.api.data.logical.Decimal\", \"version\": 1, \"default\": \"1.56\", \"parameters\": { \"scale\": \"2\" } }, \"payload\": null }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, schemaAndValue.value());
+ }
+
+ @Test
+ public void decimalToConnectOptionalWithDefaultValue() {
+ BigDecimal reference = new BigDecimal(new BigInteger("156"), 2);
+ Schema schema = Decimal.builder(2).optional().defaultValue(reference).build();
+ String msg = "{ \"schema\": { \"type\": \"bytes\", \"name\": \"io.openmessaging.connector.api.data.logical.Decimal\", \"version\": 1, \"optional\": true, \"default\": \"1.56\", \"parameters\": { \"scale\": \"2\" } }, \"payload\": null }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, schemaAndValue.value());
+ }
+
+ @Test
+ public void numericDecimalToConnect() {
+ BigDecimal reference = new BigDecimal(new BigInteger("156"), 2);
+ Schema schema = Decimal.schema(2);
+ String msg = "{ \"schema\": { \"type\": \"bytes\", \"name\": \"io.openmessaging.connector.api.data.logical.Decimal\", \"version\": 1, \"parameters\": { \"scale\": \"2\" } }, \"payload\": 1.56 }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, schemaAndValue.value());
+ }
+
+ @Test
+ public void numericDecimalWithTrailingZerosToConnect() {
+ BigDecimal reference = new BigDecimal(new BigInteger("15600"), 4);
+ Schema schema = Decimal.schema(4);
+ String msg = "{ \"schema\": { \"type\": \"bytes\", \"name\": \"io.openmessaging.connector.api.data.logical.Decimal\", \"version\": 1, \"parameters\": { \"scale\": \"4\" } }, \"payload\": 1.5600 }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, schemaAndValue.value());
+ }
+
+ @Test
+ public void highPrecisionNumericDecimalToConnect() {
+ // this number is too big to be kept in a float64!
+ BigDecimal reference = new BigDecimal("1.23456789123456789");
+ Schema schema = Decimal.schema(17);
+ String msg = "{ \"schema\": { \"type\": \"bytes\", \"name\": \"io.openmessaging.connector.api.data.logical.Decimal\", \"version\": 1, \"parameters\": { \"scale\": \"17\" } }, \"payload\": 1.23456789123456789 }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, schemaAndValue.value());
+ }
+
+ @Test
+ public void dateToConnect() {
+ Schema schema = Date.SCHEMA;
+ GregorianCalendar calendar = new GregorianCalendar(1970, Calendar.JANUARY, 1, 0, 0, 0);
+ calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
+ calendar.add(Calendar.DATE, 10000);
+ java.util.Date reference = calendar.getTime();
+ String msg = "{ \"schema\": { \"type\": \"int32\", \"name\": \"io.openmessaging.connector.api.data.logical.Date\", \"version\": 1 }, \"payload\": 10000 }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ java.util.Date converted = (java.util.Date) schemaAndValue.value();
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, converted);
+ }
+
+ @Test
+ public void dateToConnectOptional() {
+ Schema schema = Date.builder().optional().build();
+ String msg = "{ \"schema\": { \"type\": \"int32\", \"name\": \"io.openmessaging.connector.api.data.logical.Date\", \"version\": 1, \"optional\": true }, \"payload\": null }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertNull(schemaAndValue.value());
+ }
+
+ @Test
+ public void dateToConnectWithDefaultValue() {
+ java.util.Date reference = new java.util.Date(0);
+ Schema schema = Date.builder().defaultValue(reference).build();
+ String msg = "{ \"schema\": { \"type\": \"int32\", \"name\": \"io.openmessaging.connector.api.data.logical.Date\", \"version\": 1, \"default\": 0 }, \"payload\": null }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, schemaAndValue.value());
+ }
+
+ @Test
+ public void dateToConnectOptionalWithDefaultValue() {
+ java.util.Date reference = new java.util.Date(0);
+ Schema schema = Date.builder().optional().defaultValue(reference).build();
+ String msg = "{ \"schema\": { \"type\": \"int32\", \"name\": \"io.openmessaging.connector.api.data.logical.Date\", \"version\": 1, \"optional\": true, \"default\": 0 }, \"payload\": null }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, schemaAndValue.value());
+ }
+
+ @Test
+ public void timeToConnect() {
+ Schema schema = Time.SCHEMA;
+ GregorianCalendar calendar = new GregorianCalendar(1970, Calendar.JANUARY, 1, 0, 0, 0);
+ calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
+ calendar.add(Calendar.MILLISECOND, 14400000);
+ java.util.Date reference = calendar.getTime();
+ String msg = "{ \"schema\": { \"type\": \"int32\", \"name\": \"io.openmessaging.connector.api.data.logical.Time\", \"version\": 1 }, \"payload\": 14400000 }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ java.util.Date converted = (java.util.Date) schemaAndValue.value();
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, converted);
+ }
+
+ @Test
+ public void timeToConnectOptional() {
+ Schema schema = Time.builder().optional().build();
+ String msg = "{ \"schema\": { \"type\": \"int32\", \"name\": \"io.openmessaging.connector.api.data.logical.Time\", \"version\": 1, \"optional\": true }, \"payload\": null }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertNull(schemaAndValue.value());
+ }
+
+ @Test
+ public void timeToConnectWithDefaultValue() {
+ java.util.Date reference = new java.util.Date(0);
+ Schema schema = Time.builder().defaultValue(reference).build();
+ String msg = "{ \"schema\": { \"type\": \"int32\", \"name\": \"io.openmessaging.connector.api.data.logical.Time\", \"version\": 1, \"default\": 0 }, \"payload\": null }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, schemaAndValue.value());
+ }
+
+ @Test
+ public void timeToConnectOptionalWithDefaultValue() {
+ java.util.Date reference = new java.util.Date(0);
+ Schema schema = Time.builder().optional().defaultValue(reference).build();
+ String msg = "{ \"schema\": { \"type\": \"int32\", \"name\": \"io.openmessaging.connector.api.data.logical.Time\", \"version\": 1, \"optional\": true, \"default\": 0 }, \"payload\": null }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, schemaAndValue.value());
+ }
+
+ @Test
+ public void timestampToConnect() {
+ Schema schema = Timestamp.SCHEMA;
+ GregorianCalendar calendar = new GregorianCalendar(1970, Calendar.JANUARY, 1, 0, 0, 0);
+ calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
+ calendar.add(Calendar.MILLISECOND, 2000000000);
+ calendar.add(Calendar.MILLISECOND, 2000000000);
+ java.util.Date reference = calendar.getTime();
+ String msg = "{ \"schema\": { \"type\": \"int64\", \"name\": \"io.openmessaging.connector.api.data.logica.Timestamp\", \"version\": 1 }, \"payload\": 4000000000 }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ java.util.Date converted = (java.util.Date) schemaAndValue.value();
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(reference, converted);
+ }
+
+ @Test
+ public void timestampToConnectOptional() {
+ Schema schema = Timestamp.builder().optional().build();
+ String msg = "{ \"schema\": { \"type\": \"int64\", \"name\": \"io.openmessaging.connector.api.data.logica.Timestamp\", \"version\": 1, \"optional\": true }, \"payload\": null }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertNull(schemaAndValue.value());
+ }
+
+ @Test
+ public void timestampToConnectWithDefaultValue() {
+ Schema schema = Timestamp.builder().defaultValue(new java.util.Date(42)).build();
+ String msg = "{ \"schema\": { \"type\": \"int64\", \"name\": \"io.openmessaging.connector.api.data.logica.Timestamp\", \"version\": 1, \"default\": 42 }, \"payload\": null }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(new java.util.Date(42), schemaAndValue.value());
+ }
+
+ @Test
+ public void timestampToConnectOptionalWithDefaultValue() {
+ Schema schema = Timestamp.builder().optional().defaultValue(new java.util.Date(42)).build();
+ String msg = "{ \"schema\": { \"type\": \"int64\", \"name\": \"io.openmessaging.connector.api.data.logica.Timestamp\", \"version\": 1, \"optional\": true, \"default\": 42 }, \"payload\": null }";
+ SchemaAndValue schemaAndValue = converter.toConnectData(TOPIC, msg.getBytes());
+ assertEquals(schema, schemaAndValue.schema());
+ assertEquals(new java.util.Date(42), schemaAndValue.value());
+ }
+
+ // Schema metadata
+
+ @Test
+ public void testJsonSchemaMetadataTranslation() {
+ JSONObject converted= parse(converter.fromConnectData(TOPIC, SchemaBuilder.bool().build(), true));
+ assertEquals(parse("{ \"type\": \"boolean\", \"optional\": true }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals(true, converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+
+ converted = parse(converter.fromConnectData(TOPIC, SchemaBuilder.bool().build(), null));
+ assertEquals(parse("{ \"type\": \"boolean\", \"optional\": true }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+
+
+ converted = parse(converter.fromConnectData(TOPIC, SchemaBuilder.bool().required().defaultValue(true).build(), true));
+ assertEquals(parse("{ \"type\": \"boolean\", \"optional\": false, \"default\": true }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals(true, converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+
+ converted = parse(converter.fromConnectData(TOPIC, SchemaBuilder.bool().required().name("bool").version(3).doc("the documentation").parameter("foo", "bar").build(), true));
+ assertEquals(
+ parse("{ \"type\": \"boolean\", \"optional\": false, \"name\": \"bool\", \"version\": 3, \"doc\": \"the documentation\", \"parameters\": { \"foo\": \"bar\" }}"),
+ converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME)
+ );
+ assertEquals(true, converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+
+ // Schema types
+
+ @Test
+ public void booleanToJson() {
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, SchemaBuilder.bool().required().build(), true));
+ assertEquals(parse("{ \"type\": \"boolean\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals(true, converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+ @Test
+ public void byteToJson() {
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, SchemaBuilder.int8().required().build(), (byte) 12));
+ assertEquals(parse("{ \"type\": \"int8\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals(12, converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+ @Test
+ public void shortToJson() {
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, SchemaBuilder.int16().required().build(), (short) 12));
+ assertEquals(parse("{ \"type\": \"int16\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals(12, converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+ @Test
+ public void intToJson() {
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, SchemaBuilder.int32().build(), 12));
+ assertEquals(parse("{ \"type\": \"int32\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals(12, converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+ @Test
+ public void longToJson() {
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, SchemaBuilder.int64().required().build(), 4398046511104L));
+ assertEquals(parse("{ \"type\": \"int64\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals(4398046511104L, converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+ @Test
+ public void floatToJson() {
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, SchemaBuilder.float32().required().build(), 12.34f));
+ assertEquals(parse("{ \"type\": \"float\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals(12.34f, converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+ @Test
+ public void doubleToJson() {
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, SchemaBuilder.float64().required().build(), 12.34));
+ assertEquals(parse("{ \"type\": \"double\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals(12.34, converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+
+ @Test
+ public void bytesToJson(){
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, SchemaBuilder.bytes().required().build(), "test-string".getBytes()));
+ assertEquals(parse("{ \"type\": \"bytes\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ byte[] bytes = TypeUtils.castToBytes(converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME).toString());
+ assertEquals(
+ ByteBuffer.wrap("test-string".getBytes()),
+ ByteBuffer.wrap(bytes)
+ );
+ }
+
+ @Test
+ public void stringToJson() {
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, SchemaBuilder.string().required().build(), "test-string"));
+ assertEquals(parse("{ \"type\": \"string\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals("test-string", converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+ @Test
+ public void arrayToJson() {
+ Schema int32Array = SchemaBuilder.array(SchemaBuilder.int32().required().build()).required().build();
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, int32Array, Arrays.asList(1, 2, 3)));
+ assertEquals(parse("{ \"type\": \"array\", \"items\": { \"type\": \"int32\", \"optional\": false }, \"optional\": false }"),
+ converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals(Arrays.asList(1, 2, 3),
+ converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+ @Test
+ public void mapToJsonStringKeys() {
+ Schema stringIntMap = SchemaBuilder.map(SchemaBuilder.string().required().build(), SchemaBuilder.int32().required().build()).required().build();
+ Map<String, Integer> input = new HashMap<>();
+ input.put("key1", 12);
+ input.put("key2", 15);
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, stringIntMap, input));
+ assertEquals(parse("{ \"type\": \"map\", \"keys\": { \"type\" : \"string\", \"optional\": false }, \"values\": { \"type\" : \"int32\", \"optional\": false }, \"optional\": false }"),
+ converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals(
+ input,
+ converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME)
+ );
+ }
+
+ @Test
+ public void mapToJsonNonStringKeys() {
+ Schema intIntMap = SchemaBuilder.map(SchemaBuilder.int32().required().build(), SchemaBuilder.int32().required().build()).required().build();
+ Map<Integer, Integer> input = new HashMap<>();
+ input.put(1, 12);
+ input.put(2, 15);
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, intIntMap, input));
+ assertEquals(parse("{ \"type\": \"map\", \"keys\": { \"type\" : \"int32\", \"optional\": false }, \"values\": { \"type\" : \"int32\", \"optional\": false }, \"optional\": false }"),
+ converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+
+ JSONArray payload = (JSONArray) converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME);
+ assertEquals(2, payload.size());
+ Set<JSONArray> payloadEntries = new HashSet<>();
+ for (Object elem : payload.toArray()){
+ JSONArray array = (JSONArray)elem;
+ payloadEntries.add(array);
+ }
+ JSONArray values01 = new JSONArray();
+ values01.add(1); values01.add(12);
+ JSONArray values02 = new JSONArray();
+ values02.add(2); values02.add(15);
+ assertEquals(new HashSet<>(Arrays.asList(values01, values02)), payloadEntries);
+ }
+
+ @Test
+ public void structToJson() {
+ Schema schema = SchemaBuilder.struct()
+ .field("field1", SchemaBuilder.bool().required().build())
+ .field("field2", SchemaBuilder.string().required().build())
+ .field("field3", SchemaBuilder.string().required().build())
+ .field("field4", SchemaBuilder.bool().required().build())
+ .required()
+ .build();
+ Struct input = new Struct(schema).put("field1", true).put("field2", "string2").put("field3", "string3").put("field4", false);
+ JSONObject converted =(JSONObject) parseObject(converter.fromConnectData(TOPIC, schema, input));
+ JSONObject object = new JSONObject();
+ object.put("field1", true);
+ object.put("field2", "string2");
+ object.put("field3", "string3");
+ object.put("field4", false);
+ assertEquals(
+ object,
+ converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME)
+ );
+ }
+
+ @Test
+ public void structSchemaIdentical() {
+ Schema schema = SchemaBuilder.struct()
+ .field("field1", SchemaBuilder.bool().build())
+ .field("field2", SchemaBuilder.string().build())
+ .field("field3", SchemaBuilder.string().build())
+ .field("field4", SchemaBuilder.bool().build())
+ .required()
+ .build();
+ Schema inputSchema = SchemaBuilder.struct()
+ .field("field1", SchemaBuilder.bool().build())
+ .field("field2", SchemaBuilder.string().build())
+ .field("field3", SchemaBuilder.string().build())
+ .field("field4", SchemaBuilder.bool().build())
+ .required()
+ .build();
+ Struct input = new Struct(inputSchema).put("field1", true).put("field2", "string2").put("field3", "string3").put("field4", false);
+ assertStructSchemaEqual(schema, input);
+ }
+
+
+ @Test
+ public void decimalToJson() {
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, Decimal.schema(2), new BigDecimal(new BigInteger("156"), 2)));
+ assertEquals(parse("{ \"type\": \"bytes\", \"optional\": true, \"name\": \"io.openmessaging.connector.api.data.logical.Decimal\", \"version\": 1, \"parameters\": { \"scale\": \"2\" } }"),
+ converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ byte[] bytes = TypeUtils.castToBytes( converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME).toString());
+ assertArrayEquals(new byte[]{0, -100}, bytes);
+ }
+
+ @Test
+ public void decimalToNumericJson() {
+ converter.configure(Collections.singletonMap(JsonConverterConfig.DECIMAL_FORMAT_CONFIG, DecimalFormat.NUMERIC.name()));
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, Decimal.schema(2), new BigDecimal(new BigInteger("156"), 2)));
+ assertEquals(parse("{ \"type\": \"bytes\", \"optional\": true, \"name\": \"io.openmessaging.connector.api.data.logical.Decimal\", \"version\": 1, \"parameters\": { \"scale\": \"2\" } }"),
+ converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ assertEquals(new BigDecimal("1.56"), converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+
+ @Test
+ public void decimalToJsonWithoutSchema() {
+ assertThrows(
+ "expected data exception when serializing BigDecimal without schema",
+ ConnectException.class,
+ () -> converter.fromConnectData(TOPIC, null, new BigDecimal(new BigInteger("156"), 2)));
+ }
+
+ @Test
+ public void dateToJson() {
+ GregorianCalendar calendar = new GregorianCalendar(1970, Calendar.JANUARY, 1, 0, 0, 0);
+ calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
+ calendar.add(Calendar.DATE, 10000);
+ java.util.Date date = calendar.getTime();
+
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, Date.SCHEMA, date));
+ assertEquals(parse("{ \"type\": \"int32\", \"optional\": false, \"name\": \"io.openmessaging.connector.api.data.logical.Date\", \"version\": 1 }"),
+ converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ Object payload = converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME);
+ assertEquals(10000, payload);
+ }
+
+ @Test
+ public void timeToJson() {
+ GregorianCalendar calendar = new GregorianCalendar(1970, Calendar.JANUARY, 1, 0, 0, 0);
+ calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
+ calendar.add(Calendar.MILLISECOND, 14400000);
+ java.util.Date date = calendar.getTime();
+
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, Time.SCHEMA, date));
+ assertEquals(parse("{ \"type\": \"int32\", \"optional\": false, \"name\": \"io.openmessaging.connector.api.data.logical.Time\", \"version\": 1 }"),
+ converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ Object payload = converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME);
+ assertEquals(14400000, payload);
+ }
+
+ @Test
+ public void timestampToJson() {
+ GregorianCalendar calendar = new GregorianCalendar(1970, Calendar.JANUARY, 1, 0, 0, 0);
+ calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
+ calendar.add(Calendar.MILLISECOND, 2000000000);
+ calendar.add(Calendar.MILLISECOND, 2000000000);
+ java.util.Date date = calendar.getTime();
+
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, Timestamp.SCHEMA, date));
+ assertEquals(parse("{ \"type\": \"int64\", \"optional\": false, \"name\": \"io.openmessaging.connector.api.data.logica.Timestamp\", \"version\": 1 }"),
+ converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
+ Object payload = converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME);
+ assertEquals(4000000000L, payload);
+ }
+
+
+ @Test
+ public void nullSchemaAndPrimitiveToJson() {
+ // This still needs to do conversion of data, null schema means "anything goes"
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, null, true));
+ assertEquals(true, converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+ @Test
+ public void nullSchemaAndArrayToJson() {
+ // This still needs to do conversion of data, null schema means "anything goes". Make sure we mix and match
+ // types to verify conversion still works.
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, null, Arrays.asList(1, "string", true)));
+ JSONArray array = new JSONArray();
+ array.add(1);
+ array.add("string");
+ array.add(true);
+ assertEquals(
+ array,
+ converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME)
+ );
+ }
+
+ @Test
+ public void nullSchemaAndMapToJson() {
+ // This still needs to do conversion of data, null schema means "anything goes". Make sure we mix and match
+ // types to verify conversion still works.
+ Map<String, Object> input = new HashMap<>();
+ input.put("key1", 12);
+ input.put("key2", "string");
+ input.put("key3", true);
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, null, input));
+ assertEquals(input,
+ converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
+ }
+
+ @Test
+ public void nullSchemaAndMapNonStringKeysToJson() {
+ // This still needs to do conversion of data, null schema means "anything goes". Make sure we mix and match
+ // types to verify conversion still works.
+ Map<Object, Object> input = new HashMap<>();
+ input.put("string", 12);
+ input.put(52, "string");
+ input.put(false, true);
+ JSONObject converted = parse(converter.fromConnectData(TOPIC, null, input));
+ JSONArray payload = (JSONArray) converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME);
+ assertEquals(3, payload.size());
+ Set<JSONArray> payloadEntries = new HashSet<>();
+ for (Object elem : payload.toArray())
+ payloadEntries.add((JSONArray) elem);
+ }
+
+ @Test
+ public void nullSchemaAndNullValueToJson() {
+ // This characterizes the production of tombstone messages when Json schemas is enabled
+ Map<String, Boolean> props = Collections.singletonMap("schemas.enable", true);
+ converter.configure(props);
+ byte[] converted = converter.fromConnectData(TOPIC, null, null);
+ assertNull(converted);
+ }
+
+ @Test
+ public void nullValueToJson() {
+ // This characterizes the production of tombstone messages when Json schemas is not enabled
+ Map<String, Boolean> props = Collections.singletonMap("schemas.enable", false);
+ converter.configure(props);
+ byte[] converted = converter.fromConnectData(TOPIC, null, null);
+ assertNull(converted);
+ }
+
+ @Test(expected = ConnectException.class)
+ public void mismatchSchemaJson() {
+ // If we have mismatching schema info, we should properly convert to a DataException
+ converter.fromConnectData(TOPIC, SchemaBuilder.float64().build(), true);
+ }
+
+ @Test
+ public void noSchemaToConnect() {
+ Map<String, Boolean> props = Collections.singletonMap("schemas.enable", false);
+ converter.configure(props);
+ assertEquals(new SchemaAndValue(null, true), converter.toConnectData(TOPIC, "true".getBytes()));
+ }
+
+ @Test
+ public void noSchemaToJson() {
+ Map<String, Boolean> props = Collections.singletonMap("schemas.enable", false);
+ converter.configure(props);
+ byte[] result = converter.fromConnectData(TOPIC, null, true);
+ Object converted = parseObject(result);
+ assertEquals(true, converted);
+ }
+
+//
+
+ private JSONObject parse(byte[] json) {
+ try {
+ String objStr=new String(json, StandardCharsets.UTF_8);
+ return JSON.parseObject(objStr);
+ } catch (Exception e) {
+ fail("IOException during JSON parse: " + e.getMessage());
+ throw new RuntimeException("failed");
+ }
+ }
+
+ private Object parseObject(byte[] json) {
+ try {
+ String objStr=new String(json, StandardCharsets.UTF_8);
+ Object data= JSON.parse(objStr);
+ if (data instanceof JSONObject){
+ return (JSONObject)data;
+ }
+ return data;
+ } catch (Exception e) {
+ fail("IOException during JSON parse: " + e.getMessage());
+ throw new RuntimeException("failed");
+ }
+ }
+
+
+ private JSONObject parse(String json) {
+ try {
+ return JSON.parseObject(json);
+ } catch (Exception e) {
+ fail("IOException during JSON parse: " + e.getMessage());
+ throw new RuntimeException("failed");
+ }
+ }
+
+
+ private void assertStructSchemaEqual(Schema schema, Struct struct) {
+ converter.fromConnectData(TOPIC, schema, struct);
+ assertEquals(schema, struct.getSchema());
+ }
+}
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/LongConverterTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/LongConverterTest.java
new file mode 100644
index 0000000..cccfa46
--- /dev/null
+++ b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/LongConverterTest.java
@@ -0,0 +1,25 @@
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.SchemaAndValue;
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class LongConverterTest extends AbstractRecordConverterTest {
+
+
+ @Before
+ public void before(){
+ this.recordConverter = new LongConverter();
+ }
+
+
+ @Test
+ public void testIntegerConverter() {
+ Long int64 = 64L;
+ byte[] bytes = recordConverter.fromConnectData(TEST_TOPIC, SchemaBuilder.int64().build(), int64);
+ SchemaAndValue schemaAndValue = recordConverter.toConnectData(TEST_TOPIC, bytes);
+ Assert.assertEquals(schemaAndValue.value(), int64);
+ }
+}
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/ShortConverterTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/ShortConverterTest.java
new file mode 100644
index 0000000..86f7014
--- /dev/null
+++ b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/ShortConverterTest.java
@@ -0,0 +1,25 @@
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.SchemaAndValue;
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class ShortConverterTest extends AbstractRecordConverterTest {
+
+
+ @Before
+ public void before(){
+ this.recordConverter = new ShortConverter();
+ }
+
+
+ @Test
+ public void testShortConverter() {
+ Short int16 = 16;
+ byte[] bytes = recordConverter.fromConnectData(TEST_TOPIC, SchemaBuilder.int16().build(), int16);
+ SchemaAndValue schemaAndValue = recordConverter.toConnectData(TEST_TOPIC, bytes);
+ Assert.assertEquals(schemaAndValue.value(), int16);
+ }
+}
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/StringConverterTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/StringConverterTest.java
new file mode 100644
index 0000000..f6bb74f
--- /dev/null
+++ b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/converter/record/StringConverterTest.java
@@ -0,0 +1,25 @@
+package org.apache.rocketmq.connect.runtime.converter.record;
+
+import io.openmessaging.connector.api.data.SchemaAndValue;
+import io.openmessaging.connector.api.data.SchemaBuilder;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class StringConverterTest extends AbstractRecordConverterTest {
+
+
+ @Before
+ public void before(){
+ this.recordConverter = new StringConverter();
+ }
+
+
+ @Test
+ public void testStringConverter() {
+ String str = "test_converter";
+ byte[] bytes = recordConverter.fromConnectData(TEST_TOPIC, SchemaBuilder.string().build(), str);
+ SchemaAndValue schemaAndValue = recordConverter.toConnectData(TEST_TOPIC, bytes);
+ Assert.assertEquals(schemaAndValue.value(), str);
+ }
+}
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/rest/RestHandlerTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/rest/RestHandlerTest.java
index 509f609..098601b 100644
--- a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/rest/RestHandlerTest.java
+++ b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/rest/RestHandlerTest.java
@@ -22,7 +22,7 @@ import com.alibaba.fastjson.JSONObject;
import io.openmessaging.connector.api.component.connector.Connector;
import io.openmessaging.connector.api.component.task.source.SourceTask;
import io.openmessaging.connector.api.data.ConnectRecord;
-import io.openmessaging.connector.api.data.Converter;
+import io.openmessaging.connector.api.data.RecordConverter;
import io.openmessaging.internal.DefaultKeyValue;
import java.net.URI;
import java.nio.ByteBuffer;
@@ -96,7 +96,7 @@ public class RestHandlerTest {
private SourceTask sourceTask;
@Mock
- private Converter converter;
+ private RecordConverter converter;
@Mock
private PositionManagementServiceImpl positionManagementServiceImpl;
diff --git a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/store/FileBaseKeyValueStoreTest.java b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/store/FileBaseKeyValueStoreTest.java
index 041b868..123fc7f 100644
--- a/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/store/FileBaseKeyValueStoreTest.java
+++ b/rocketmq-connect-runtime/src/test/java/org/apache/rocketmq/connect/runtime/store/FileBaseKeyValueStoreTest.java
@@ -18,6 +18,7 @@
package org.apache.rocketmq.connect.runtime.store;
import java.util.HashMap;
+
import org.apache.rocketmq.connect.runtime.converter.ByteConverter;
import org.junit.Test;