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 import org.apache.logging.log4j.core.util.StringEncoder;
24
25
26
27
28
29
30
31
32 public abstract class AbstractCsvLayout extends AbstractStringLayout {
33
34 protected static final String DEFAULT_CHARSET = "UTF-8";
35 protected static final String DEFAULT_FORMAT = "Default";
36 private static final String CONTENT_TYPE = "text/csv";
37 private static final long serialVersionUID = 1L;
38
39 private final CSVFormat format;
40
41 protected AbstractCsvLayout(final Charset charset, final CSVFormat csvFormat, final String header,
42 final String footer) {
43 super(charset, StringEncoder.toBytes(header, charset), StringEncoder.toBytes(footer, charset));
44 this.format = csvFormat;
45 }
46
47 protected static CSVFormat createFormat(final String format, final Character delimiter, final Character escape,
48 final Character quote, final QuoteMode quoteMode, final String nullString, final String recordSeparator) {
49 CSVFormat csvFormat = CSVFormat.valueOf(format);
50 if (delimiter != null) {
51 csvFormat = csvFormat.withDelimiter(delimiter);
52 }
53 if (escape != null) {
54 csvFormat = csvFormat.withEscape(escape);
55 }
56 if (quote != null) {
57 csvFormat = csvFormat.withQuote(quote);
58 }
59 if (quoteMode != null) {
60 csvFormat = csvFormat.withQuoteMode(quoteMode);
61 }
62 if (nullString != null) {
63 csvFormat = csvFormat.withNullString(nullString);
64 }
65 if (recordSeparator != null) {
66 csvFormat = csvFormat.withRecordSeparator(recordSeparator);
67 }
68 return csvFormat;
69 }
70
71 @Override
72 public String getContentType() {
73 return CONTENT_TYPE + "; charset=" + this.getCharset();
74 }
75
76 public CSVFormat getFormat() {
77 return format;
78 }
79 }