001package jmri.jmrit.operations.rollingstock; 002 003import java.io.*; 004import java.nio.charset.StandardCharsets; 005import java.util.Arrays; 006 007import javax.swing.*; 008import javax.swing.filechooser.FileNameExtensionFilter; 009 010import org.apache.commons.csv.*; 011import org.slf4j.Logger; 012import org.slf4j.LoggerFactory; 013 014import jmri.jmrit.operations.setup.Control; 015 016/** 017 * Provides common routes for importing cars and locomotives 018 * 019 * @author Dan Boudreau Copyright (C) 2013 020 * 021 */ 022public abstract class ImportRollingStock extends Thread { 023 024 protected static final String NEW_LINE = "\n"; // NOI18N 025 026 protected JLabel lineNumber = new JLabel(); 027 protected JLabel importLine = new JLabel(); 028 029 protected static final String LOCATION_TRACK_SEPARATOR = "-"; 030 031 protected jmri.util.JmriJFrame fstatus; 032 033 // Get file to read from 034 protected File getFile() { 035 JFileChooser fc = new jmri.util.swing.JmriJFileChooser(jmri.jmrit.operations.OperationsXml.getFileLocation()); 036 fc.setFileFilter(new FileNameExtensionFilter(Bundle.getMessage("Text&CSV"), "txt", "csv")); // NOI18N 037 int retVal = fc.showOpenDialog(null); 038 if (retVal != JFileChooser.APPROVE_OPTION) { 039 return null; // canceled 040 } 041 log.info("Importing from file: {}", fc.getSelectedFile()); 042 return fc.getSelectedFile(); 043 } 044 045 protected BufferedReader getBufferedReader(File file) { 046 try { 047 return new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); 048 } catch (FileNotFoundException e) { 049 return null; 050 } 051 } 052 053 // create a status frame showing line number and imported text 054 protected void createStatusFrame(String title) { 055 JPanel ps = new JPanel(); 056 ps.setLayout(new BoxLayout(ps, BoxLayout.Y_AXIS)); 057 fstatus = new jmri.util.JmriJFrame(title); 058 fstatus.setLocation(10, 10); 059 fstatus.setSize(Control.panelWidth1025, 100); 060 061 ps.add(lineNumber); 062 ps.add(importLine); 063 064 fstatus.getContentPane().add(ps); 065 fstatus.setVisible(true); 066 } 067 068 /* 069 * Needs to handle empty lines 070 */ 071 protected String[] parseCommaLine(String line) { 072 String[] outLine = new String[0]; 073 try { 074 CSVRecord record = CSVParser.parse(line, CSVFormat.DEFAULT).getRecords().get(0); 075 outLine = new String[record.size()]; 076 // load output array to prevent NPE 077 for (int i = 0; i < outLine.length; i++) { 078 outLine[i] = record.get(i); 079 } 080 } catch (IndexOutOfBoundsException e) { 081 // do nothing blank line 082 } catch (IOException ex) { 083 log.error("Error parsing CSV: {}, {}", line, ex.getLocalizedMessage()); 084 Arrays.fill(outLine, ""); // NOI18N 085 } 086 return outLine; 087 } 088 089 private final static Logger log = LoggerFactory.getLogger(ImportRollingStock.class); 090}