View Javadoc
1   /*
2    * Copyright 2007 Kasper B. Graversen
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.supercsv.quote;
17  
18  import java.util.HashSet;
19  import java.util.Set;
20  
21  import org.supercsv.prefs.CsvPreference;
22  import org.supercsv.util.CsvContext;
23  
24  /**
25   * When using ColumnQuoteMode surrounding quotes are only applied if required to escape special characters (per
26   * RFC4180), or if a particular column should always be quoted.
27   * 
28   * @author James Bassett
29   * @since 2.1.0
30   */
31  public class ColumnQuoteMode implements QuoteMode {
32  	
33  	private final Set<Integer> columnNumbers = new HashSet<Integer>();
34  	
35  	/**
36  	 * Constructs a new <tt>ColumnQuoteMode</tt> that quotes columns by column number. If no column numbers are supplied
37  	 * (i.e. no parameters) then quoting will be determined per RFC4180.
38  	 * 
39  	 * @param columnsToQuote
40  	 *            the column numbers to quote
41  	 */
42  	public ColumnQuoteMode(final int... columnsToQuote) {
43  		if( columnsToQuote == null ) {
44  			throw new NullPointerException("columnsToQuote should not be null");
45  		}
46  		for( final Integer columnToQuote : columnsToQuote ) {
47  			columnNumbers.add(columnToQuote);
48  		}
49  	}
50  	
51  	/**
52  	 * Constructs a new <tt>ColumnQuoteMode</tt> that quotes columns if the element representing that column in the
53  	 * supplied array is true. Please note that <tt>false</tt> doesn't disable quoting, it just means that quoting is
54  	 * determined by RFC4180.
55  	 * 
56  	 * @param columnsToQuote
57  	 *            array of booleans (one per CSV column) indicating whether each column should be quoted or not
58  	 * @throws NullPointerException
59  	 *             if columnsToQuote is null
60  	 */
61  	public ColumnQuoteMode(final boolean[] columnsToQuote) {
62  		if( columnsToQuote == null ) {
63  			throw new NullPointerException("columnsToQuote should not be null");
64  		}
65  		for( int i = 0; i < columnsToQuote.length; i++ ) {
66  			if( columnsToQuote[i] ) {
67  				columnNumbers.add(i + 1); // column numbers start at 1
68  			}
69  		}
70  	}
71  	
72  	/**
73  	 * {@inheritDoc}
74  	 */
75  	public boolean quotesRequired(final String csvColumn, final CsvContext context, final CsvPreference preference) {
76  		return columnNumbers.contains(context.getColumnNumber());
77  	}
78  	
79  }