001 /* 002 * SonarQube, open source software quality management tool. 003 * Copyright (C) 2008-2014 SonarSource 004 * mailto:contact AT sonarsource DOT com 005 * 006 * SonarQube is free software; you can redistribute it and/or 007 * modify it under the terms of the GNU Lesser General Public 008 * License as published by the Free Software Foundation; either 009 * version 3 of the License, or (at your option) any later version. 010 * 011 * SonarQube is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 014 * Lesser General Public License for more details. 015 * 016 * You should have received a copy of the GNU Lesser General Public License 017 * along with this program; if not, write to the Free Software Foundation, 018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 019 */ 020 package org.sonar.api.utils.text; 021 022 import org.apache.commons.lang.StringEscapeUtils; 023 024 import java.io.IOException; 025 import java.io.Writer; 026 027 /** 028 * @since 4.2 029 */ 030 public class CsvWriter { 031 032 private final Writer writer; 033 private static final String VALUE_SEPARATOR = ",", LINE_SEPARATOR = "\r\n"; 034 035 private CsvWriter(Writer writer) { 036 this.writer = writer; 037 } 038 039 public static CsvWriter of(Writer writer) { 040 return new CsvWriter(writer); 041 } 042 043 public CsvWriter values(String... values) { 044 for (int index = 0; index < values.length; index++) { 045 if (index > 0) { 046 write(VALUE_SEPARATOR); 047 } 048 String value = values[index]; 049 if (value != null) { 050 write(StringEscapeUtils.escapeCsv(value)); 051 } 052 if (index == values.length - 1) { 053 write(LINE_SEPARATOR); 054 } 055 } 056 return this; 057 } 058 059 public void close() { 060 try { 061 writer.close(); 062 } catch (IOException e) { 063 throw new WriterException("Fail to close CSV output", e); 064 } 065 } 066 067 private void write(String s) { 068 try { 069 writer.append(s); 070 } catch (IOException e) { 071 throw new WriterException("Fail to generate CSV with value: " + s, e); 072 } 073 } 074 }