Search in sources :

Example 1 with DataEntryBuilder

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

the class JdbcSourceTask method poll.

@Override
public Collection<SourceDataEntry> poll() {
    List<SourceDataEntry> res = new ArrayList<>();
    try {
        if (tableQueue.size() > 1)
            querier = tableQueue.poll(1000, TimeUnit.MILLISECONDS);
        else
            querier = tableQueue.peek();
        Timer timer = new Timer();
        try {
            Thread.currentThread();
            // 毫秒
            Thread.sleep(1000);
        } catch (Exception e) {
            throw e;
        }
        querier.poll();
        for (Table dataRow : querier.getList()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("nextQuery", "database");
            jsonObject.put("nextPosition", "table");
            Schema schema = new Schema();
            schema.setDataSource(dataRow.getDatabase());
            schema.setName(dataRow.getName());
            schema.setFields(new ArrayList<>());
            for (int i = 0; i < dataRow.getColList().size(); i++) {
                String columnName = dataRow.getColList().get(i);
                String rawDataType = dataRow.getRawDataTypeList().get(i);
                Field field = new Field(i, columnName, ColumnParser.mapConnectorFieldType(rawDataType));
                schema.getFields().add(field);
            }
            DataEntryBuilder dataEntryBuilder = new DataEntryBuilder(schema);
            dataEntryBuilder.timestamp(System.currentTimeMillis()).queue(dataRow.getName()).entryType(EntryType.UPDATE);
            for (int i = 0; i < dataRow.getColList().size(); i++) {
                Object[] value = new Object[2];
                value[0] = value[1] = dataRow.getParserList().get(i).getValue(dataRow.getDataList().get(i));
                dataEntryBuilder.putFiled(dataRow.getColList().get(i), JSONObject.toJSONString(value));
            }
            SourceDataEntry sourceDataEntry = dataEntryBuilder.buildSourceDataEntry(ByteBuffer.wrap((ConstDefine.PREFIX + config.getDbUrl() + config.getDbPort()).getBytes(StandardCharsets.UTF_8)), ByteBuffer.wrap(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8)));
            res.add(sourceDataEntry);
            log.debug("sourceDataEntry : {}", JSONObject.toJSONString(sourceDataEntry));
        }
    } catch (Exception e) {
        log.error("JDBC task poll error, current config:" + JSON.toJSONString(config), e);
    }
    log.debug("dataEntry poll successfully,{}", JSONObject.toJSONString(res));
    return res;
}
Also used : SourceDataEntry(io.openmessaging.connector.api.data.SourceDataEntry) Table(org.apache.rocketmq.connect.jdbc.schema.Table) Schema(io.openmessaging.connector.api.data.Schema) DataEntryBuilder(io.openmessaging.connector.api.data.DataEntryBuilder) Field(io.openmessaging.connector.api.data.Field) JSONObject(com.alibaba.fastjson.JSONObject) JSONObject(com.alibaba.fastjson.JSONObject)

Example 2 with DataEntryBuilder

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

the class MongoDataEntry method createSouceDataEntry.

public static SourceDataEntry createSouceDataEntry(ReplicationEvent event, ReplicaSetConfig replicaSetConfig) {
    DataEntryBuilder dataEntryBuilder;
    if (event.getOperationType().equals(OperationType.CREATED)) {
        Schema schema = createdSchema(replicaSetConfig.getReplicaSetName());
        dataEntryBuilder = new DataEntryBuilder(schema);
        dataEntryBuilder.timestamp(System.currentTimeMillis()).queue(event.getNamespace().replace(".", "-").replace("$", "-")).entryType(event.getEntryType());
        dataEntryBuilder.putFiled(CREATED, event.getDocument().toJson());
        dataEntryBuilder.putFiled(NAMESPACE, event.getNamespace());
    } else {
        Schema schema = oplogSchema(replicaSetConfig.getReplicaSetName());
        dataEntryBuilder = new DataEntryBuilder(schema);
        dataEntryBuilder.timestamp(System.currentTimeMillis()).queue(event.getNamespace().replace(".", "-").replace("$", "-")).entryType(event.getEntryType());
        dataEntryBuilder.putFiled(OPERATION_TYPE, event.getOperationType().name());
        dataEntryBuilder.putFiled(TIMESTAMP, event.getTimestamp().getValue());
        dataEntryBuilder.putFiled(VERSION, event.getV());
        dataEntryBuilder.putFiled(NAMESPACE, event.getNamespace());
        dataEntryBuilder.putFiled(PATCH, event.getEventData().isPresent() ? JSONObject.toJSONString(event.getEventData().get()) : "");
        dataEntryBuilder.putFiled(OBJECT_ID, event.getObjectId().isPresent() ? JSONObject.toJSONString(event.getObjectId().get()) : "");
    }
    String position = createPosition(event, replicaSetConfig);
    SourceDataEntry sourceDataEntry = dataEntryBuilder.buildSourceDataEntry(ByteBuffer.wrap(replicaSetConfig.getReplicaSetName().getBytes(StandardCharsets.UTF_8)), ByteBuffer.wrap(position.getBytes(StandardCharsets.UTF_8)));
    return sourceDataEntry;
}
Also used : SourceDataEntry(io.openmessaging.connector.api.data.SourceDataEntry) Schema(io.openmessaging.connector.api.data.Schema) DataEntryBuilder(io.openmessaging.connector.api.data.DataEntryBuilder)

Example 3 with DataEntryBuilder

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

the class FileSourceTask method poll.

@Override
public Collection<SourceDataEntry> poll() {
    log.info("Start a poll stream is null:{}", stream == null);
    if (stream == null) {
        try {
            stream = Files.newInputStream(Paths.get(fileConfig.getFilename()));
            ByteBuffer positionInfo;
            positionInfo = this.context.positionStorageReader().getPosition(ByteBuffer.wrap(FileConstants.getPartition(fileConfig.getFilename()).getBytes(Charset.defaultCharset())));
            if (positionInfo != null) {
                log.info("positionInfo is not null!");
                String positionJson = new String(positionInfo.array(), Charset.defaultCharset());
                JSONObject jsonObject = JSONObject.parseObject(positionJson);
                Object lastRecordedOffset = jsonObject.getLong(FileConstants.NEXT_POSITION);
                if (lastRecordedOffset != null && !(lastRecordedOffset instanceof Long))
                    throw new ConnectException(-1, "Offset position is the incorrect type");
                if (lastRecordedOffset != null) {
                    log.debug("Found previous offset, trying to skip to file offset {}", lastRecordedOffset);
                    long skipLeft = (Long) lastRecordedOffset;
                    while (skipLeft > 0) {
                        try {
                            long skipped = stream.skip(skipLeft);
                            skipLeft -= skipped;
                        } catch (IOException e) {
                            log.error("Error while trying to seek to previous offset in file {}: ", fileConfig.getFilename(), e);
                            throw new ConnectException(-1, e);
                        }
                    }
                    log.debug("Skipped to offset {}", lastRecordedOffset);
                }
                streamOffset = (lastRecordedOffset != null) ? (Long) lastRecordedOffset : 0L;
            } else {
                log.info("positionInfo is null!");
                streamOffset = 0L;
            }
            reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
            log.debug("Opened {} for reading", logFilename());
        } catch (NoSuchFileException e) {
            log.warn("Couldn't find file {} for FileStreamSourceTask, sleeping to wait for it to be created", logFilename());
            synchronized (this) {
                try {
                    this.wait(1000);
                } catch (InterruptedException e1) {
                    log.error("Interrupt error .", e1);
                }
            }
            return null;
        } catch (IOException e) {
            log.error("Error while trying to open file {}: ", fileConfig.getFilename(), e);
            throw new ConnectException(-1, e);
        }
    }
    try {
        final BufferedReader readerCopy;
        synchronized (this) {
            readerCopy = reader;
        }
        if (readerCopy == null) {
            return null;
        }
        Collection<SourceDataEntry> records = null;
        int nread = 0;
        while (readerCopy.ready()) {
            nread = readerCopy.read(buffer, offset, buffer.length - offset);
            log.trace("Read {} bytes from {}", nread, logFilename());
            if (nread > 0) {
                offset += nread;
                if (offset == buffer.length) {
                    char[] newbuf = new char[buffer.length * 2];
                    System.arraycopy(buffer, 0, newbuf, 0, buffer.length);
                    buffer = newbuf;
                }
                String line;
                do {
                    line = extractLine();
                    if (line != null) {
                        log.trace("Read a line from {}", logFilename());
                        if (records == null) {
                            records = new ArrayList<>();
                        }
                        Schema schema = new Schema();
                        schema.setDataSource(fileConfig.getFilename());
                        schema.setName(fileConfig.getFilename() + LINE);
                        final Field field = new Field(0, FileConstants.FILE_LINE_CONTENT, FieldType.STRING);
                        List<Field> fields = new ArrayList<Field>() {

                            {
                                add(field);
                            }
                        };
                        schema.setFields(fields);
                        DataEntryBuilder dataEntryBuilder = new DataEntryBuilder(schema).entryType(EntryType.CREATE).queue(fileConfig.getTopic()).timestamp(System.currentTimeMillis()).putFiled(FileConstants.FILE_LINE_CONTENT, line);
                        final SourceDataEntry sourceDataEntry = dataEntryBuilder.buildSourceDataEntry(offsetKey(FileConstants.getPartition(fileConfig.getFilename())), offsetValue(streamOffset));
                        records.add(sourceDataEntry);
                        if (records.size() >= batchSize) {
                            return records;
                        }
                    }
                } while (line != null);
            }
        }
        if (nread <= 0) {
            synchronized (this) {
                this.wait(1000);
            }
        }
        return records;
    } catch (IOException e) {
    } catch (InterruptedException e) {
        log.error("Interrupt error .", e);
    }
    return null;
}
Also used : SourceDataEntry(io.openmessaging.connector.api.data.SourceDataEntry) InputStreamReader(java.io.InputStreamReader) Schema(io.openmessaging.connector.api.data.Schema) NoSuchFileException(java.nio.file.NoSuchFileException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) DataEntryBuilder(io.openmessaging.connector.api.data.DataEntryBuilder) ByteBuffer(java.nio.ByteBuffer) Field(io.openmessaging.connector.api.data.Field) JSONObject(com.alibaba.fastjson.JSONObject) BufferedReader(java.io.BufferedReader) JSONObject(com.alibaba.fastjson.JSONObject) ConnectException(io.openmessaging.connector.api.exception.ConnectException)

Example 4 with DataEntryBuilder

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

the class MetaSourceTask method poll.

@Override
public Collection<SourceDataEntry> poll() {
    log.debug("polling...");
    List<String> groups = JSONObject.parseArray(this.config.getTaskGroupList(), String.class);
    if (groups == null) {
        log.info("no group in task.");
        try {
            Thread.sleep(TimeUnit.SECONDS.toMillis(10));
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
        return Collections.emptyList();
    }
    List<SourceDataEntry> res = new ArrayList<>();
    for (String group : groups) {
        ConsumeStats stats;
        try {
            stats = this.srcMQAdminExt.examineConsumeStats(group);
        } catch (Exception e) {
            log.error("admin get consumer info failed for consumer groups: " + group, e);
            continue;
        }
        for (Map.Entry<MessageQueue, OffsetWrapper> offsetTable : stats.getOffsetTable().entrySet()) {
            MessageQueue mq = offsetTable.getKey();
            long srcOffset = offsetTable.getValue().getConsumerOffset();
            long targetOffset = this.store.convertTargetOffset(mq, group, srcOffset);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(RmqConstants.NEXT_POSITION, srcOffset);
            Schema schema = new Schema();
            schema.setDataSource(this.config.getSourceRocketmq());
            schema.setName(mq.getTopic());
            schema.setFields(new ArrayList<>());
            schema.getFields().add(new Field(0, FieldName.OFFSET.getKey(), FieldType.INT64));
            DataEntryBuilder dataEntryBuilder = new DataEntryBuilder(schema);
            dataEntryBuilder.timestamp(System.currentTimeMillis()).queue(this.config.getStoreTopic()).entryType(EntryType.UPDATE);
            dataEntryBuilder.putFiled(FieldName.OFFSET.getKey(), targetOffset);
            SourceDataEntry sourceDataEntry = dataEntryBuilder.buildSourceDataEntry(ByteBuffer.wrap(RmqConstants.getPartition(mq.getTopic(), mq.getBrokerName(), String.valueOf(mq.getQueueId())).getBytes(StandardCharsets.UTF_8)), ByteBuffer.wrap(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8)));
            String targetTopic = new StringBuilder().append(group).append("-").append(mq.getTopic()).append("-").append(mq.getQueueId()).toString();
            sourceDataEntry.setQueueName(targetTopic);
            res.add(sourceDataEntry);
        }
    }
    return res;
}
Also used : SourceDataEntry(io.openmessaging.connector.api.data.SourceDataEntry) ConsumeStats(org.apache.rocketmq.common.admin.ConsumeStats) Schema(io.openmessaging.connector.api.data.Schema) ArrayList(java.util.ArrayList) DataEntryBuilder(io.openmessaging.connector.api.data.DataEntryBuilder) MQClientException(org.apache.rocketmq.client.exception.MQClientException) OffsetWrapper(org.apache.rocketmq.common.admin.OffsetWrapper) Field(io.openmessaging.connector.api.data.Field) MessageQueue(org.apache.rocketmq.common.message.MessageQueue) JSONObject(com.alibaba.fastjson.JSONObject) Map(java.util.Map)

Example 5 with DataEntryBuilder

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

the class CassandraSourceTask method poll.

@Override
public Collection<SourceDataEntry> poll() {
    List<SourceDataEntry> res = new ArrayList<>();
    try {
        if (tableQueue.size() > 1)
            querier = tableQueue.poll(1000, TimeUnit.MILLISECONDS);
        else
            querier = tableQueue.peek();
        Timer timer = new Timer();
        try {
            Thread.currentThread();
            // 毫秒
            Thread.sleep(1000);
        } catch (Exception e) {
            throw e;
        }
        querier.poll();
        for (Table dataRow : querier.getList()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("nextQuery", "database");
            jsonObject.put("nextPosition", "table");
            Schema schema = new Schema();
            schema.setDataSource(dataRow.getDatabase());
            schema.setName(dataRow.getName());
            schema.setFields(new ArrayList<>());
            for (int i = 0; i < dataRow.getColList().size(); i++) {
                String columnName = dataRow.getColList().get(i);
                String rawDataType = dataRow.getRawDataTypeList().get(i);
                Field field = new Field(i, columnName, ColumnParser.mapConnectorFieldType(rawDataType));
                schema.getFields().add(field);
            }
            DataEntryBuilder dataEntryBuilder = new DataEntryBuilder(schema);
            dataEntryBuilder.timestamp(System.currentTimeMillis()).queue(dataRow.getName()).entryType(EntryType.UPDATE);
            for (int i = 0; i < dataRow.getColList().size(); i++) {
                Object[] value = new Object[2];
                value[0] = value[1] = dataRow.getParserList().get(i).getValue(dataRow.getDataList().get(i));
                dataEntryBuilder.putFiled(dataRow.getColList().get(i), JSONObject.toJSONString(value));
            }
            SourceDataEntry sourceDataEntry = dataEntryBuilder.buildSourceDataEntry(ByteBuffer.wrap((ConstDefine.PREFIX + config.getDbUrl() + config.getDbPort()).getBytes(StandardCharsets.UTF_8)), ByteBuffer.wrap(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8)));
            res.add(sourceDataEntry);
            log.debug("sourceDataEntry : {}", JSONObject.toJSONString(sourceDataEntry));
        }
    } catch (Exception e) {
        log.error("Cassandra task poll error, current config:" + JSON.toJSONString(config), e);
    }
    log.debug("dataEntry poll successfully,{}", JSONObject.toJSONString(res));
    return res;
}
Also used : SourceDataEntry(io.openmessaging.connector.api.data.SourceDataEntry) Table(org.apache.rocketmq.connect.cassandra.schema.Table) Schema(io.openmessaging.connector.api.data.Schema) ArrayList(java.util.ArrayList) DataEntryBuilder(io.openmessaging.connector.api.data.DataEntryBuilder) Field(io.openmessaging.connector.api.data.Field) Timer(java.util.Timer) JSONObject(com.alibaba.fastjson.JSONObject) JSONObject(com.alibaba.fastjson.JSONObject)

Aggregations

DataEntryBuilder (io.openmessaging.connector.api.data.DataEntryBuilder)9 Schema (io.openmessaging.connector.api.data.Schema)8 SourceDataEntry (io.openmessaging.connector.api.data.SourceDataEntry)8 Field (io.openmessaging.connector.api.data.Field)5 ArrayList (java.util.ArrayList)5 JSONObject (com.alibaba.fastjson.JSONObject)4 SinkDataEntry (io.openmessaging.connector.api.data.SinkDataEntry)2 ByteBuffer (java.nio.ByteBuffer)2 EntryType (io.openmessaging.connector.api.data.EntryType)1 ConnectException (io.openmessaging.connector.api.exception.ConnectException)1 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 NoSuchFileException (java.nio.file.NoSuchFileException)1 Map (java.util.Map)1 Timer (java.util.Timer)1 MQClientException (org.apache.rocketmq.client.exception.MQClientException)1 ConsumeStats (org.apache.rocketmq.common.admin.ConsumeStats)1 OffsetWrapper (org.apache.rocketmq.common.admin.OffsetWrapper)1 MessageQueue (org.apache.rocketmq.common.message.MessageQueue)1