com.blockhaus2000.csvviewer.CsvViewerMain.java Source code

Java tutorial

Introduction

Here is the source code for com.blockhaus2000.csvviewer.CsvViewerMain.java

Source

/* This file is part of the csv-viewer.
 *
 * Copyright (C) 2014-2015 Fabian Damken
 *
 * This program is frese software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.blockhaus2000.csvviewer;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;

import com.blockhaus2000.simpletable.Table;
import com.blockhaus2000.simpletable.TableRow;
import com.blockhaus2000.simpletable.TableRowCell;

public class CsvViewerMain {
    public static void main(final String[] args) {
        try (final CSVParser parser = new CSVParser(new InputStreamReader(System.in), CSVFormat.DEFAULT)) {
            final Table table = new Table();

            final Map<String, Integer> headerMap = parser.getHeaderMap();
            if (headerMap != null) {
                final TableRow headerRow = new TableRow();
                headerMap.keySet().forEach(headerData -> headerRow.addCell(new TableRowCell(headerData)));
                table.setHeaderRow(headerRow);
            }

            final AtomicBoolean asHeader = new AtomicBoolean(headerMap == null);
            parser.getRecords().forEach(record -> {
                final TableRow row = new TableRow();
                record.forEach(rowData -> row.addCell(new TableRowCell(rowData)));
                if (asHeader.getAndSet(false)) {
                    table.setHeaderRow(row);
                } else {
                    table.addRow(row);
                }
            });

            System.out.println(table.getFormattedString());
        } catch (final IOException cause) {
            throw new RuntimeException("An error occurred whilst parsing stdin!", cause);
        }
    }
}