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 private static final String CONTENT_TYPE = "text/csv"; 034 protected static final String DEFAULT_CHARSET = "UTF-8"; 035 protected static final String DEFAULT_FORMAT = "Default"; 036 private static final long serialVersionUID = 1L; 037 038 protected static CSVFormat createFormat(final String format, final Character delimiter, final Character escape, final Character quote, final QuoteMode quoteMode, final String nullString, 039 final String recordSeparator) { 040 CSVFormat csvFormat = CSVFormat.valueOf(format); 041 if (delimiter != null) { 042 csvFormat = csvFormat.withDelimiter(delimiter); 043 } 044 if (escape != null) { 045 csvFormat = csvFormat.withEscape(escape); 046 } 047 if (quote != null) { 048 csvFormat = csvFormat.withQuote(quote); 049 } 050 if (quoteMode != null) { 051 csvFormat = csvFormat.withQuoteMode(quoteMode); 052 } 053 if (nullString != null) { 054 csvFormat = csvFormat.withNullString(nullString); 055 } 056 if (recordSeparator != null) { 057 csvFormat = csvFormat.withRecordSeparator(recordSeparator); 058 } 059 return csvFormat; 060 } 061 062 private final CSVFormat format; 063 064 protected AbstractCsvLayout(final Charset charset, final CSVFormat csvFormat, final String header, 065 final String footer) { 066 super(charset, toBytes(header, charset), toBytes(footer, charset)); 067 this.format = 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 079}