1 package fr.ifremer.tutti.service.csv;
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 import com.google.common.base.Charsets;
28 import com.google.common.base.Preconditions;
29 import com.google.common.io.Files;
30 import org.apache.commons.lang3.builder.ToStringBuilder;
31 import org.apache.commons.logging.Log;
32 import org.apache.commons.logging.LogFactory;
33 import org.nuiton.jaxx.application.ApplicationTechnicalException;
34
35 import java.io.BufferedWriter;
36 import java.io.Closeable;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.nio.file.Path;
40 import java.util.ArrayList;
41 import java.util.Collections;
42 import java.util.List;
43
44
45
46
47
48
49
50 public abstract class CsvProducer<O, M extends AbstractTuttiImportExportModel<O>> implements Closeable {
51
52
53 private static final Log log = LogFactory.getLog(CsvProducer.class);
54
55 private final BufferedWriter writer;
56
57 private final TuttiRepeatableExport<O> export;
58
59 private boolean touch;
60
61 private final String filename;
62
63 public CsvProducer(Path file, M model) {
64
65 Preconditions.checkNotNull(file, "CsvProducer need a not null file!");
66 Preconditions.checkNotNull(model, "CsvProducer need a not null model!");
67
68 this.filename = file.toString();
69
70 try {
71 this.writer = Files.newWriter(file.toFile(), Charsets.UTF_8);
72 } catch (FileNotFoundException e) {
73
74 throw new ApplicationTechnicalException("file not found " + file, e);
75 }
76
77 this.export = new TuttiRepeatableExport<>(model);
78
79 }
80
81 @Override
82 public void close() throws IOException {
83 writer.close();
84 }
85
86 public void write(O row) throws Exception {
87 if (row != null) {
88 List<O> rows = new ArrayList<>(1);
89 rows.add(row);
90 write(rows);
91 }
92 }
93
94 public void write(List<O> rows) throws Exception {
95 if (rows != null) {
96 if (!touch) {
97
98 if (log.isDebugEnabled()) {
99 log.debug("CsvProducer " + this + " touched.");
100 }
101 touch = true;
102
103 }
104 export.write(rows, writer);
105 }
106 }
107
108 public void writeEmpty() throws Exception {
109 write(Collections.<O>emptyList());
110 }
111
112 public boolean wasTouched() {
113 return touch;
114 }
115
116 @Override
117 public String toString() {
118 return new ToStringBuilder(this).append("filename", filename).toString();
119 }
120 }