001package jmri.jmrit.symbolicprog; 002 003import java.awt.event.ActionEvent; 004import java.io.File; 005import java.io.FileOutputStream; 006import java.io.IOException; 007import java.io.OutputStreamWriter; 008import java.nio.charset.StandardCharsets; 009import javax.swing.AbstractAction; 010import javax.swing.JFileChooser; 011import javax.swing.JFrame; 012import org.apache.commons.csv.CSVFormat; 013import org.apache.commons.csv.CSVPrinter; 014import org.slf4j.Logger; 015import org.slf4j.LoggerFactory; 016 017/** 018 * Action to export the CV values to a Comma Separated Variable (CSV) data file. 019 * 020 * @author Bob Jacobsen Copyright (C) 2023 021 */ 022public class CsvExportVariablesAction extends AbstractAction { 023 024 public CsvExportVariablesAction(String actionName, VariableTableModel pModel, JFrame pParent) { 025 super(actionName); 026 mModel = pModel; 027 mParent = pParent; 028 } 029 030 JFileChooser fileChooser; 031 JFrame mParent; 032 033 /** 034 * VariableTableModel to load 035 */ 036 VariableTableModel mModel; 037 038 @Override 039 public void actionPerformed(ActionEvent e) { 040 041 if (fileChooser == null) { 042 fileChooser = new jmri.util.swing.JmriJFileChooser(); 043 } 044 045 int retVal = fileChooser.showSaveDialog(mParent); 046 047 if (retVal == JFileChooser.APPROVE_OPTION) { 048 File file = fileChooser.getSelectedFile(); 049 if (log.isDebugEnabled()) { 050 log.debug("start to export to CSV file {}", file); 051 } 052 053 try (CSVPrinter str = new CSVPrinter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), CSVFormat.DEFAULT)) { 054 str.printRecord("Variable", "value"); 055 for (int i = 0; i < mModel.getRowCount(); i++) { 056 VariableValue var = mModel.getVariable(i); 057 if (isWritable(var)) { 058 var name = var.label(); 059 var value = var.getValueString(); 060 str.printRecord(name, value); 061 } 062 } 063 str.flush(); 064 } catch (IOException ex) { 065 log.error("Error writing file", ex); 066 } 067 } 068 } 069 070 /** 071 * Decide whether a given Variable should be written out. 072 * @param var Variable to be checked 073 * @return true if Variable should be included in output file. 074 */ 075 protected boolean isWritable(VariableValue var) { 076 return true; 077 } 078 079 080 private final static Logger log = LoggerFactory.getLogger(CsvExportVariablesAction.class); 081}