Search in sources :

Example 1 with EntryType

use of io.openmessaging.connector.api.data.EntryType in project rocketmq-externals by apache.

the class CassandraSinkTask method put.

@Override
public void put(Collection<SinkDataEntry> sinkDataEntries) {
    try {
        if (tableQueue.size() > 1) {
            updater = tableQueue.poll(1000, TimeUnit.MILLISECONDS);
        } else {
            updater = tableQueue.peek();
        }
        log.info("Cassandra Sink Task trying to put()");
        for (SinkDataEntry record : sinkDataEntries) {
            Map<Field, Object[]> fieldMap = new HashMap<>();
            Object[] payloads = record.getPayload();
            Schema schema = record.getSchema();
            EntryType entryType = record.getEntryType();
            String cfName = schema.getName();
            String keyspaceName = schema.getDataSource();
            List<Field> fields = schema.getFields();
            Boolean parseError = false;
            if (!fields.isEmpty()) {
                for (Field field : fields) {
                    Object fieldValue = payloads[field.getIndex()];
                    Object[] value = JSONObject.parseArray((String) fieldValue).toArray();
                    if (value.length == 2) {
                        fieldMap.put(field, value);
                    } else {
                        log.error("parseArray error, fieldValue:{}", fieldValue);
                        parseError = true;
                    }
                }
            }
            if (!parseError) {
                log.info("Cassandra Sink Task trying to call updater.push()");
                Boolean isSuccess = updater.push(keyspaceName, cfName, fieldMap, entryType);
                if (!isSuccess) {
                    log.error("push data error, keyspaceName:{}, cfName:{}, entryType:{}, fieldMap:{}", keyspaceName, cfName, fieldMap, entryType);
                }
            }
        }
    } catch (Exception e) {
        log.error("put sinkDataEntries error, {}", e);
    }
}
Also used : Field(io.openmessaging.connector.api.data.Field) SinkDataEntry(io.openmessaging.connector.api.data.SinkDataEntry) EntryType(io.openmessaging.connector.api.data.EntryType) HashMap(java.util.HashMap) Schema(io.openmessaging.connector.api.data.Schema) JSONObject(com.alibaba.fastjson.JSONObject)

Example 2 with EntryType

use of io.openmessaging.connector.api.data.EntryType in project rocketmq-externals by apache.

the class MongoTest method testInitSyncCopy.

@Test
public void testInitSyncCopy() throws NoSuchFieldException, IllegalAccessException, InterruptedException {
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("person");
    collection.deleteMany(new Document());
    int count = 1000;
    List<String> documents = new ArrayList<>(count);
    for (int i = 0; i < count; i++) {
        Document document = new Document();
        document.put("name", "test" + i);
        document.put("age", i);
        document.put("sex", i % 2 == 0 ? "boy" : "girl");
        collection.insertOne(document);
        documents.add(document.getObjectId("_id").toHexString());
    }
    SourceTaskConfig sourceTaskConfig = new SourceTaskConfig();
    Map<String, List<String>> insterest = new HashMap<>();
    List<String> collections = new ArrayList<>();
    collections.add("*");
    insterest.put("test", collections);
    sourceTaskConfig.setInterestDbAndCollection(JSONObject.toJSONString(insterest));
    ReplicaSetConfig replicaSetConfig = new ReplicaSetConfig("", "test", "localhost");
    ReplicaSetsContext replicaSetsContext = new ReplicaSetsContext(sourceTaskConfig);
    ReplicaSet replicaSet = new ReplicaSet(replicaSetConfig, replicaSetsContext);
    Field running = ReplicaSet.class.getDeclaredField("running");
    running.setAccessible(true);
    running.set(replicaSet, new AtomicBoolean(true));
    InitSync initSync = new InitSync(replicaSetConfig, mongoClient, replicaSetsContext, replicaSet);
    initSync.start();
    int syncCount = 0;
    while (syncCount < count) {
        Collection<SourceDataEntry> sourceDataEntries = replicaSetsContext.poll();
        Assert.assertTrue(sourceDataEntries.size() > 0);
        for (SourceDataEntry sourceDataEntry : sourceDataEntries) {
            ByteBuffer sourcePartition = sourceDataEntry.getSourcePartition();
            Assert.assertEquals("test", new String(sourcePartition.array()));
            ByteBuffer sourcePosition = sourceDataEntry.getSourcePosition();
            Position position = new Position();
            position.setInitSync(true);
            position.setTimeStamp(0);
            position.setInc(0);
            Assert.assertEquals(position, JSONObject.parseObject(new String(sourcePosition.array()), Position.class));
            EntryType entryType = sourceDataEntry.getEntryType();
            Assert.assertEquals(EntryType.CREATE, entryType);
            String queueName = sourceDataEntry.getQueueName();
            Assert.assertEquals("test-person", queueName);
            Schema schema = sourceDataEntry.getSchema();
            Assert.assertTrue(schema.getFields().size() == 2);
            Object[] payload = sourceDataEntry.getPayload();
            Assert.assertTrue(payload.length == 2);
            Assert.assertEquals(payload[0].toString(), "test.person");
            Assert.assertTrue(documents.contains(JSONObject.parseObject(payload[1].toString(), Document.class).get("_id", JSONObject.class).getString("$oid")));
            syncCount++;
        }
    }
    Assert.assertTrue(syncCount == count);
}
Also used : HashMap(java.util.HashMap) Schema(io.openmessaging.connector.api.data.Schema) ArrayList(java.util.ArrayList) ConnectionString(com.mongodb.ConnectionString) Document(org.bson.Document) Field(java.lang.reflect.Field) ArrayList(java.util.ArrayList) List(java.util.List) ReplicaSet(org.apache.connect.mongo.replicator.ReplicaSet) SourceDataEntry(io.openmessaging.connector.api.data.SourceDataEntry) Position(org.apache.connect.mongo.replicator.Position) ReplicaSetsContext(org.apache.connect.mongo.replicator.ReplicaSetsContext) ByteBuffer(java.nio.ByteBuffer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) InitSync(org.apache.connect.mongo.initsync.InitSync) EntryType(io.openmessaging.connector.api.data.EntryType) ReplicaSetConfig(org.apache.connect.mongo.replicator.ReplicaSetConfig) JSONObject(com.alibaba.fastjson.JSONObject) JSONObject(com.alibaba.fastjson.JSONObject) Test(org.junit.Test)

Example 3 with EntryType

use of io.openmessaging.connector.api.data.EntryType in project rocketmq-externals by apache.

the class WorkerSourceTask method sendRecord.

/**
 * Send list of sourceDataEntries to MQ.
 *
 * @param sourceDataEntries
 */
private void sendRecord(Collection<SourceDataEntry> sourceDataEntries) {
    for (SourceDataEntry sourceDataEntry : sourceDataEntries) {
        ByteBuffer partition = sourceDataEntry.getSourcePartition();
        Optional<ByteBuffer> opartition = Optional.ofNullable(partition);
        ByteBuffer position = sourceDataEntry.getSourcePosition();
        Optional<ByteBuffer> oposition = Optional.ofNullable(position);
        sourceDataEntry.setSourcePartition(null);
        sourceDataEntry.setSourcePosition(null);
        Message sourceMessage = new Message();
        sourceMessage.setTopic(sourceDataEntry.getQueueName());
        if (null == recordConverter || recordConverter instanceof RocketMQConverter) {
            if (StringUtils.isNotEmpty(sourceDataEntry.getShardingKey())) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_SHARDINGKEY, sourceDataEntry.getShardingKey());
            }
            if (StringUtils.isNotEmpty(sourceDataEntry.getQueueName())) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_TOPICNAME, sourceDataEntry.getQueueName());
            }
            if (opartition.isPresent()) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_SOURCE_PARTITION, new String(opartition.get().array()));
            }
            if (oposition.isPresent()) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_SOURCE_POSITION, new String(oposition.get().array()));
            }
            EntryType entryType = sourceDataEntry.getEntryType();
            Optional<EntryType> oentryType = Optional.ofNullable(entryType);
            if (oentryType.isPresent()) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_ENTRYTYPE, oentryType.get().name());
            }
            Long timestamp = sourceDataEntry.getTimestamp();
            Optional<Long> otimestamp = Optional.ofNullable(timestamp);
            if (otimestamp.isPresent()) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_TIMESTAMP, otimestamp.get().toString());
            }
            Schema schema = sourceDataEntry.getSchema();
            Optional<Schema> oschema = Optional.ofNullable(schema);
            if (oschema.isPresent()) {
                MessageAccessor.putProperty(sourceMessage, RuntimeConfigDefine.CONNECT_SCHEMA, JSON.toJSONString(oschema.get()));
            }
            Object[] payload = sourceDataEntry.getPayload();
            if (null != payload && null != payload[0]) {
                Object object = payload[0];
                final byte[] messageBody = (String.valueOf(object)).getBytes();
                if (messageBody.length > RuntimeConfigDefine.MAX_MESSAGE_SIZE) {
                    log.error("Send record, message size is greater than {} bytes, payload: {}", RuntimeConfigDefine.MAX_MESSAGE_SIZE, sourceDataEntry.getPayload());
                    return;
                }
                sourceMessage.setBody(messageBody);
            }
        } else {
            byte[] payload = recordConverter.objectToByte(sourceDataEntry.getPayload());
            Object[] newPayload = new Object[1];
            newPayload[0] = Base64.getEncoder().encodeToString(payload);
            sourceDataEntry.setPayload(newPayload);
            final byte[] messageBody = JSON.toJSONString(sourceDataEntry).getBytes();
            if (messageBody.length > RuntimeConfigDefine.MAX_MESSAGE_SIZE) {
                log.error("Send record, message size is greater than {} bytes, payload: {}", RuntimeConfigDefine.MAX_MESSAGE_SIZE, sourceDataEntry.getPayload());
                return;
            }
            sourceMessage.setBody(messageBody);
        }
        try {
            producer.send(sourceMessage, new SendCallback() {

                @Override
                public void onSuccess(org.apache.rocketmq.client.producer.SendResult result) {
                    log.info("Successful send message to RocketMQ:{}", result.getMsgId());
                    try {
                        if (null != partition && null != position) {
                            positionManagementService.putPosition(partition, position);
                        }
                    } catch (Exception e) {
                        log.error("Source task save position info failed.", e);
                    }
                }

                @Override
                public void onException(Throwable throwable) {
                    if (null != throwable) {
                        log.error("Source task send record failed {}.", throwable);
                    }
                }
            });
        } catch (MQClientException e) {
            log.error("Send message error. message: {}, error info: {}.", sourceMessage, e);
        } catch (RemotingException e) {
            log.error("Send message error. message: {}, error info: {}.", sourceMessage, e);
        } catch (InterruptedException e) {
            log.error("Send message error. message: {}, error info: {}.", sourceMessage, e);
        }
    }
}
Also used : Message(org.apache.rocketmq.common.message.Message) Schema(io.openmessaging.connector.api.data.Schema) MQClientException(org.apache.rocketmq.client.exception.MQClientException) SourceDataEntry(io.openmessaging.connector.api.data.SourceDataEntry) ByteBuffer(java.nio.ByteBuffer) RocketMQConverter(org.apache.rocketmq.connect.runtime.converter.RocketMQConverter) MQClientException(org.apache.rocketmq.client.exception.MQClientException) RemotingException(org.apache.rocketmq.remoting.exception.RemotingException) EntryType(io.openmessaging.connector.api.data.EntryType) RemotingException(org.apache.rocketmq.remoting.exception.RemotingException) SendCallback(org.apache.rocketmq.client.producer.SendCallback)

Example 4 with EntryType

use of io.openmessaging.connector.api.data.EntryType in project rocketmq-externals by apache.

the class WorkerSinkTask method convertToSinkDataEntry.

private SinkDataEntry convertToSinkDataEntry(MessageExt message) {
    Map<String, String> properties = message.getProperties();
    String queueName;
    EntryType entryType;
    Schema schema;
    Long timestamp;
    Object[] datas = new Object[1];
    if (null == recordConverter || recordConverter instanceof RocketMQConverter) {
        queueName = properties.get(RuntimeConfigDefine.CONNECT_TOPICNAME);
        String connectEntryType = properties.get(RuntimeConfigDefine.CONNECT_ENTRYTYPE);
        entryType = StringUtils.isNotEmpty(connectEntryType) ? EntryType.valueOf(connectEntryType) : null;
        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;
        datas = new Object[1];
        datas[0] = message.getBody();
    } else {
        final byte[] messageBody = message.getBody();
        final SourceDataEntry sourceDataEntry = JSON.parseObject(new String(messageBody), SourceDataEntry.class);
        final Object[] payload = sourceDataEntry.getPayload();
        final byte[] decodeBytes = Base64.getDecoder().decode((String) payload[0]);
        Object recodeObject;
        if (recordConverter instanceof JsonConverter) {
            JsonConverter jsonConverter = (JsonConverter) recordConverter;
            jsonConverter.setClazz(Object[].class);
            recodeObject = recordConverter.byteToObject(decodeBytes);
            datas = (Object[]) recodeObject;
        }
        schema = sourceDataEntry.getSchema();
        entryType = sourceDataEntry.getEntryType();
        queueName = sourceDataEntry.getQueueName();
        timestamp = sourceDataEntry.getTimestamp();
    }
    DataEntryBuilder dataEntryBuilder = new DataEntryBuilder(schema);
    dataEntryBuilder.entryType(entryType);
    dataEntryBuilder.queue(queueName);
    dataEntryBuilder.timestamp(timestamp);
    List<Field> fields = schema.getFields();
    if (null != fields && !fields.isEmpty()) {
        for (Field field : fields) {
            dataEntryBuilder.putFiled(field.getName(), datas[field.getIndex()]);
        }
    }
    SinkDataEntry sinkDataEntry = dataEntryBuilder.buildSinkDataEntry(message.getQueueOffset());
    return sinkDataEntry;
}
Also used : SourceDataEntry(io.openmessaging.connector.api.data.SourceDataEntry) JsonConverter(org.apache.rocketmq.connect.runtime.converter.JsonConverter) Schema(io.openmessaging.connector.api.data.Schema) DataEntryBuilder(io.openmessaging.connector.api.data.DataEntryBuilder) RocketMQConverter(org.apache.rocketmq.connect.runtime.converter.RocketMQConverter) Field(io.openmessaging.connector.api.data.Field) SinkDataEntry(io.openmessaging.connector.api.data.SinkDataEntry) EntryType(io.openmessaging.connector.api.data.EntryType)

Example 5 with EntryType

use of io.openmessaging.connector.api.data.EntryType in project rocketmq-externals by apache.

the class JdbcSinkTask method put.

@Override
public void put(Collection<SinkDataEntry> sinkDataEntries) {
    try {
        if (tableQueue.size() > 1) {
            updater = tableQueue.poll(1000, TimeUnit.MILLISECONDS);
        } else {
            updater = tableQueue.peek();
        }
        for (SinkDataEntry record : sinkDataEntries) {
            Map<Field, Object[]> fieldMap = new HashMap<>();
            Object[] payloads = record.getPayload();
            Schema schema = record.getSchema();
            EntryType entryType = record.getEntryType();
            String tableName = schema.getName();
            String dbName = schema.getDataSource();
            List<Field> fields = schema.getFields();
            Boolean parseError = false;
            if (!fields.isEmpty()) {
                for (Field field : fields) {
                    Object fieldValue = payloads[field.getIndex()];
                    Object[] value = JSONObject.parseArray((String) fieldValue).toArray();
                    if (value.length == 2) {
                        fieldMap.put(field, value);
                    } else {
                        log.error("parseArray error, fieldValue:{}", fieldValue);
                        parseError = true;
                    }
                }
            }
            if (!parseError) {
                Boolean isSuccess = updater.push(dbName, tableName, fieldMap, entryType);
                if (!isSuccess) {
                    log.error("push data error, dbName:{}, tableName:{}, entryType:{}, fieldMap:{}", dbName, tableName, fieldMap, entryType);
                }
            }
        }
    } catch (Exception e) {
        log.error("put sinkDataEntries error, {}", e);
    }
}
Also used : Field(io.openmessaging.connector.api.data.Field) SinkDataEntry(io.openmessaging.connector.api.data.SinkDataEntry) EntryType(io.openmessaging.connector.api.data.EntryType) HashMap(java.util.HashMap) Schema(io.openmessaging.connector.api.data.Schema) JSONObject(com.alibaba.fastjson.JSONObject)

Aggregations

EntryType (io.openmessaging.connector.api.data.EntryType)6 Schema (io.openmessaging.connector.api.data.Schema)6 JSONObject (com.alibaba.fastjson.JSONObject)4 SourceDataEntry (io.openmessaging.connector.api.data.SourceDataEntry)4 Field (io.openmessaging.connector.api.data.Field)3 SinkDataEntry (io.openmessaging.connector.api.data.SinkDataEntry)3 ByteBuffer (java.nio.ByteBuffer)3 HashMap (java.util.HashMap)3 Field (java.lang.reflect.Field)2 List (java.util.List)2 Position (org.apache.connect.mongo.replicator.Position)2 ReplicaSetConfig (org.apache.connect.mongo.replicator.ReplicaSetConfig)2 ReplicaSetsContext (org.apache.connect.mongo.replicator.ReplicaSetsContext)2 RocketMQConverter (org.apache.rocketmq.connect.runtime.converter.RocketMQConverter)2 Document (org.bson.Document)2 Test (org.junit.Test)2 ConnectionString (com.mongodb.ConnectionString)1 DataEntryBuilder (io.openmessaging.connector.api.data.DataEntryBuilder)1 ArrayList (java.util.ArrayList)1 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)1