1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.layout;
18
19 import java.nio.charset.Charset;
20
21 import org.apache.commons.csv.CSVFormat;
22 import org.apache.commons.csv.QuoteMode;
23
24
25
26
27
28
29
30
31 public abstract class AbstractCsvLayout extends AbstractStringLayout {
32
33 protected static final String DEFAULT_CHARSET = "UTF-8";
34 protected static final String DEFAULT_FORMAT = "Default";
35 private static final String CONTENT_TYPE = "text/csv";
36 private static final long serialVersionUID = 1L;
37
38 private final CSVFormat format;
39
40 protected AbstractCsvLayout(final Charset charset, final CSVFormat csvFormat, final String header,
41 final String footer) {
42 super(charset, toBytes(header, charset), toBytes(footer, charset));
43 this.format = csvFormat;
44 }
45
46 protected static CSVFormat createFormat(final String format, final Character delimiter, final Character escape,
47 final Character quote, final QuoteMode quoteMode, final String nullString, final String recordSeparator) {
48 CSVFormat csvFormat = CSVFormat.valueOf(format);
49 if (delimiter != null) {
50 csvFormat = csvFormat.withDelimiter(delimiter);
51 }
52 if (escape != null) {
53 csvFormat = csvFormat.withEscape(escape);
54 }
55 if (quote != null) {
56 csvFormat = csvFormat.withQuote(quote);
57 }
58 if (quoteMode != null) {
59 csvFormat = csvFormat.withQuoteMode(quoteMode);
60 }
61 if (nullString != null) {
62 csvFormat = csvFormat.withNullString(nullString);
63 }
64 if (recordSeparator != null) {
65 csvFormat = csvFormat.withRecordSeparator(recordSeparator);
66 }
67 return csvFormat;
68 }
69
70 @Override
71 public String getContentType() {
72 return CONTENT_TYPE + "; charset=" + this.getCharset();
73 }
74
75 public CSVFormat getFormat() {
76 return format;
77 }
78 }