shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.walker.di.univocity;
 
import com.univocity.parsers.common.processor.ObjectRowWriterProcessor;
import com.univocity.parsers.csv.CsvWriter;
import com.univocity.parsers.csv.CsvWriterSettings;
import com.walker.di.AbstractErrorWriter;
import com.walker.di.Constants;
import com.walker.infrastructure.utils.KeyValue;
 
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
 
/**
 * CSV方式实现的错误记录器。
 * @author 时克英
 * @date 2023-02-02
 */
public class CsvErrorWriter extends AbstractErrorWriter {
 
    private CsvWriter writer = null;
    private OutputStream outputStream = null;
 
    public CsvErrorWriter(OutputStream outputStream, List<String> fieldNames){
        this.outputStream = outputStream;
        // 加入最后一列: 错误原因
        String[] columns = this.cloneColumns(fieldNames);
        final CsvWriterSettings csvWriterSettings = new CsvWriterSettings();
        csvWriterSettings.setHeaderWritingEnabled(Boolean.TRUE);
        csvWriterSettings.setRowWriterProcessor(new ObjectRowWriterProcessor());
        csvWriterSettings.setHeaders(columns);
        writer = new CsvWriter(outputStream, csvWriterSettings);
    }
 
    @Override
//    public void write(Map<String, String> data, String error) {
    public void write(List<KeyValue<String, String>> data, String error) {
        if(writer != null){
//            data.put(Constants.ERROR_COLUMN_NAME, error);
            data.add(new KeyValue<>(Constants.ERROR_COLUMN_NAME, error));
 
//            // 数据转 Map
//            Map<String, String> map = new HashMap<>();
//            for(KeyValue<String, String> kv : data){
//                map.put(kv.getKey(), kv.getValue());
//            }
//            this.writer.processRecord(data);
            this.writer.processRecord(this.toMap(data));
            logger.debug("error = " + data);
        } else {
            logger.warn("writer不存在");
        }
    }
 
    @Override
    public void close() {
        if(this.writer != null){
            this.writer.close();
        }
        if(this.outputStream != null){
            try {
                this.outputStream.close();
            } catch (IOException e) {}
        }
    }
}