001/*
002 * SonarQube
003 * Copyright (C) 2009-2017 SonarSource SA
004 * mailto:info AT sonarsource DOT com
005 *
006 * This program 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 * This program 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 */
020package org.sonar.api.utils.text;
021
022import org.apache.commons.lang.StringEscapeUtils;
023
024import java.io.IOException;
025import java.io.Writer;
026
027/**
028 * @since 4.2
029 */
030public class CsvWriter {
031
032  private final Writer writer;
033  private static final String VALUE_SEPARATOR = ",";
034  private static final String LINE_SEPARATOR = "\r\n";
035
036  private CsvWriter(Writer writer) {
037    this.writer = writer;
038  }
039
040  public static CsvWriter of(Writer writer) {
041    return new CsvWriter(writer);
042  }
043
044  public CsvWriter values(String... values) {
045    for (int index = 0; index < values.length; index++) {
046      if (index > 0) {
047        write(VALUE_SEPARATOR);
048      }
049      String value = values[index];
050      if (value != null) {
051        write(StringEscapeUtils.escapeCsv(value));
052      }
053      if (index == values.length - 1) {
054        write(LINE_SEPARATOR);
055      }
056    }
057    return this;
058  }
059
060  public void close() {
061    try {
062      writer.close();
063    } catch (IOException e) {
064      throw new WriterException("Fail to close CSV output", e);
065    }
066  }
067
068  private void write(String s) {
069    try {
070      writer.append(s);
071    } catch (IOException e) {
072      throw new WriterException("Fail to generate CSV with value: " + s, e);
073    }
074  }
075}