001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017package org.apache.logging.log4j.core.layout; 018 019import java.nio.charset.Charset; 020 021import org.apache.commons.csv.CSVFormat; 022import org.apache.commons.csv.QuoteMode; 023 024/** 025 * A superclass for Comma-Separated Value (CSV) layouts. 026 * 027 * Depends on Apache Commons CSV 1.2. 028 * 029 * @since 2.4 030 */ 031public abstract class AbstractCsvLayout extends AbstractStringLayout { 032 033 protected static final String DEFAULT_CHARSET = "UTF-8"; 034 protected static final String DEFAULT_FORMAT = "Default"; 035 private static final String CONTENT_TYPE = "text/csv"; 036 private static final long serialVersionUID = 1L; 037 038 private final CSVFormat format; 039 040 protected AbstractCsvLayout(final Charset charset, final CSVFormat csvFormat, final String header, 041 final String footer) { 042 super(charset, toBytes(header, charset), toBytes(footer, charset)); 043 this.format = csvFormat; 044 } 045 046 protected static CSVFormat createFormat(final String format, final Character delimiter, final Character escape, 047 final Character quote, final QuoteMode quoteMode, final String nullString, final String recordSeparator) { 048 CSVFormat csvFormat = CSVFormat.valueOf(format); 049 if (delimiter != null) { 050 csvFormat = csvFormat.withDelimiter(delimiter); 051 } 052 if (escape != null) { 053 csvFormat = csvFormat.withEscape(escape); 054 } 055 if (quote != null) { 056 csvFormat = csvFormat.withQuote(quote); 057 } 058 if (quoteMode != null) { 059 csvFormat = csvFormat.withQuoteMode(quoteMode); 060 } 061 if (nullString != null) { 062 csvFormat = csvFormat.withNullString(nullString); 063 } 064 if (recordSeparator != null) { 065 csvFormat = csvFormat.withRecordSeparator(recordSeparator); 066 } 067 return csvFormat; 068 } 069 070 @Override 071 public String getContentType() { 072 return CONTENT_TYPE + "; charset=" + this.getCharset(); 073 } 074 075 public CSVFormat getFormat() { 076 return format; 077 } 078}