File: CSVQuoter.java

package info (click to toggle)
libbase 1.1.6-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 944 kB
  • sloc: java: 8,709; xml: 1,522; makefile: 18
file content (262 lines) | stat: -rw-r--r-- 6,722 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/*
 * This program is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
 * Foundation.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
 * or from the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * Copyright (c) 2007 - 2009 Pentaho Corporation and Contributors.  All rights reserved.
 */

package org.pentaho.reporting.libraries.base.util;

import java.io.Writer;
import java.io.IOException;

/**
 * The <code>CSVQuoter</code> is a helper class to encode a string for the CSV file
 * format.
 *
 * @author Thomas Morgner.
 */
public final class CSVQuoter
{
  /**
   * The separator used in the CSV file.
   */
  private char separator;
  /**
   * The quoting character or a single quote.
   */
  private char quate;
  /**
   * The double quote. This is a string containing the quate two times.
   */
  private String doubleQuate;

  /**
   * Creates a new CSVQuoter, which uses a comma as the default separator.
   */
  public CSVQuoter()
  {
    this(',', '"');
  }

  /**
   * Creates a new <code>CSVQuoter</code>, which uses the defined separator.
   *
   * @param separator the separator.
   * @throws NullPointerException if the given separator is <code>null</code>.
   */
  public CSVQuoter(final char separator)
  {
    this(separator,  '"');
  }

  /**
   * Creates a new CSVQuoter with the given separator and quoting character.
   *
   * @param separator the separator
   * @param quate the quoting character
   */
  public CSVQuoter(final char separator, final char quate)
  {
    this.separator = separator;
    this.quate = quate;
    this.doubleQuate = String.valueOf(quate) + quate;
  }

  /**
   * Encodes the string, so that the string can safely be used in CSV files. If the string
   * does not need quoting, the original string is returned unchanged.
   *
   * @param original the unquoted string.
   * @return The quoted string
   */
  public String doQuoting (final String original)
  {
    if (isQuotingNeeded(original))
    {
      final StringBuffer retval = new StringBuffer(original.length() + 5); // a safe guess most of the time.
      retval.append(quate);
      applyQuote(retval, original);
      retval.append(quate);
      return retval.toString();
    }
    else
    {
      return original;
    }
  }

  /**
   * A streaming version of the quoting algorithm for more performance. Encodes the string, so that the string can
   * safely be used in CSV files. If the string does not need quoting, the original string is returned unchanged.
   * 
   * @param original the unquoted string.
   * @param writer the writer.
   * @throws IOException if an IO error occured.
   */
  public void doQuoting (final String original, final Writer writer) throws IOException
  {
    if (isQuotingNeeded(original))
    {
      writer.write(quate);
      applyQuote(writer, original);
      writer.write(quate);
    }
    else
    {
      writer.write(original);
    }
  }

  /**
   * Decodes the string, so that all escape sequences get removed. If the string was not
   * quoted, then the string is returned unchanged.
   *
   * @param nativeString the quoted string.
   * @return The unquoted string.
   */
  public String undoQuoting (final String nativeString)
  {
    if (isQuotingNeeded(nativeString))
    {
      final StringBuffer b = new StringBuffer(nativeString.length());
      final int length = nativeString.length() - 1;
      int start = 1;

      int pos = start;
      while (pos != -1)
      {
        pos = nativeString.indexOf(doubleQuate, start);
        if (pos == -1)
        {
          b.append(nativeString.substring(start, length));
        }
        else
        {
          b.append(nativeString.substring(start, pos));
          start = pos + 1;
        }
      }
      return b.toString();
    }
    else
    {
      return nativeString;
    }
  }

  /**
   * Tests, whether this string needs to be quoted. A string is encoded if the string
   * contains a newline character, a quote character or the defined separator.
   *
   * @param str the string that should be tested.
   * @return true, if quoting needs to be applied, false otherwise.
   */
  private boolean isQuotingNeeded (final String str)
  {
    final int length = str.length();
    for (int i = 0; i < length; i++)
    {
      final char c = str.charAt(i);
      if (c == separator)
      {
        return true;
      }
      if (c == '\n')
      {
        return true;
      }
      if (c == quate)
      {
        return true;
      }
    }
    return false;
  }

  /**
   * Applies the quoting to a given string, and stores the result in the StringBuffer
   * <code>b</code>.
   *
   * @param b        the result buffer
   * @param original the string, that should be quoted.
   */
  private void applyQuote (final StringBuffer b, final String original)
  {
    // This solution needs improvements. Copy blocks instead of single
    // characters.
    final int length = original.length();

    for (int i = 0; i < length; i++)
    {
      final char c = original.charAt(i);
      if (c == quate)
      {
        b.append(doubleQuate);
      }
      else
      {
        b.append(c);
      }
    }
  }


  /**
   * Applies the quoting to a given string, and stores the result in the StringBuffer
   * <code>b</code>.
   *
   * @param b        the result buffer
   * @param original the string, that should be quoted.
   * @throws IOException if an IO-Error occured.
   */
  private void applyQuote (final Writer b, final String original) throws IOException
  {
    // This solution needs improvements. Copy blocks instead of single
    // characters.
    final int length = original.length();

    for (int i = 0; i < length; i++)
    {
      final char c = original.charAt(i);
      if (c == quate)
      {
        b.write(doubleQuate);
      }
      else
      {
        b.write(c);
      }
    }
  }

  /**
   * Gets the separator used in this quoter and the CSV file.
   *
   * @return the separator (never <code>null</code>).
   */
  public char getSeparator ()
  {
    return separator;
  }

  /**
   * Returns the quoting character.
   *
   * @return the quote character.
   */
  public char getQuate ()
  {
    return quate;
  }
}