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; 023import org.apache.logging.log4j.core.util.StringEncoder; 024 025/** 026 * A superclass for Comma-Separated Value (CSV) layouts. 027 * 028 * Depends on Apache Commons CSV 1.2. 029 * 030 * @since 2.4 031 */ 032public abstract class AbstractCsvLayout extends AbstractStringLayout { 033 034 protected static final String DEFAULT_CHARSET = "UTF-8"; 035 protected static final String DEFAULT_FORMAT = "Default"; 036 private static final String CONTENT_TYPE = "text/csv"; 037 private static final long serialVersionUID = 1L; 038 039 private final CSVFormat format; 040 041 protected AbstractCsvLayout(final Charset charset, final CSVFormat csvFormat, final String header, 042 final String footer) { 043 super(charset, StringEncoder.toBytes(header, charset), StringEncoder.toBytes(footer, charset)); 044 this.format = csvFormat; 045 } 046 047 protected static CSVFormat createFormat(final String format, final Character delimiter, final Character escape, 048 final Character quote, final QuoteMode quoteMode, final String nullString, final String recordSeparator) { 049 CSVFormat csvFormat = CSVFormat.valueOf(format); 050 if (delimiter != null) { 051 csvFormat = csvFormat.withDelimiter(delimiter); 052 } 053 if (escape != null) { 054 csvFormat = csvFormat.withEscape(escape); 055 } 056 if (quote != null) { 057 csvFormat = csvFormat.withQuote(quote); 058 } 059 if (quoteMode != null) { 060 csvFormat = csvFormat.withQuoteMode(quoteMode); 061 } 062 if (nullString != null) { 063 csvFormat = csvFormat.withNullString(nullString); 064 } 065 if (recordSeparator != null) { 066 csvFormat = csvFormat.withRecordSeparator(recordSeparator); 067 } 068 return csvFormat; 069 } 070 071 @Override 072 public String getContentType() { 073 return CONTENT_TYPE + "; charset=" + this.getCharset(); 074 } 075 076 public CSVFormat getFormat() { 077 return format; 078 } 079}