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.encoder; 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 * A selective CsvEncoder implementation - only the desired column numbers (if any) are encoded. Use with caution - 26 * disabling encoding may increase performance but at the risk of invalid CSV. 27 * 28 * @author James Bassett 29 * @since 2.1.0 30 */ 31 public class SelectiveCsvEncoder extends DefaultCsvEncoder { 32 33 private final Set<Integer> columnNumbers = new HashSet<Integer>(); 34 35 /** 36 * Constructs a new <tt>SelectiveCsvEncoder</tt> that encodes columns by column number. If no column numbers are 37 * supplied (i.e. no parameters) then no columns will be encoded. 38 * 39 * @param columnsToEncode 40 * the column numbers to encode 41 */ 42 public SelectiveCsvEncoder(final int... columnsToEncode) { 43 if( columnsToEncode == null ) { 44 throw new NullPointerException("columnsToEncode should not be null"); 45 } 46 for( final Integer columnToEncode : columnsToEncode ) { 47 columnNumbers.add(columnToEncode); 48 } 49 } 50 51 /** 52 * Constructs a new <tt>SelectiveCsvEncoder</tt> that encodes columns if the element representing that column in the 53 * supplied array is true. 54 * 55 * @param columnsToEncode 56 * boolean array representing columns to encode (true indicates a column should be encoded). 57 */ 58 public SelectiveCsvEncoder(final boolean[] columnsToEncode) { 59 if( columnsToEncode == null ) { 60 throw new NullPointerException("columnsToEncode should not be null"); 61 } 62 for( int i = 0; i < columnsToEncode.length; i++ ) { 63 if( columnsToEncode[i] ) { 64 columnNumbers.add(i + 1); // column numbers start at 1 65 } 66 } 67 } 68 69 /** 70 * {@inheritDoc} 71 */ 72 public String encode(final String input, final CsvContext context, final CsvPreference preference) { 73 return columnNumbers.contains(context.getColumnNumber()) ? super.encode(input, context, preference) : input; 74 75 } 76 77 }