001package jmri.jmrit.operations.rollingstock.engines.tools;
002
003import java.io.*;
004import java.nio.charset.StandardCharsets;
005import java.util.List;
006
007import org.apache.commons.csv.CSVFormat;
008import org.apache.commons.csv.CSVPrinter;
009
010import jmri.InstanceManager;
011import jmri.jmrit.XmlFile;
012import jmri.jmrit.operations.rollingstock.engines.Engine;
013import jmri.jmrit.operations.rollingstock.engines.EngineManager;
014import jmri.jmrit.operations.setup.OperationsSetupXml;
015import jmri.jmrit.operations.setup.Setup;
016import jmri.util.swing.JmriJOptionPane;
017
018/**
019 * Exports the Engine roster into a comma delimited file (CSV). Order stored:
020 * Number, Road, Model, Length, Owner, Built, Location, -, Track, Consist,
021 * Moves, Last, Value, HP, Weight, Type, Comment, Misc.
022 *
023 * @author Daniel Boudreau Copyright (C) 2010
024 *
025 */
026public class ExportEngines extends XmlFile {
027
028    protected static final String LOCATION_TRACK_SEPARATOR = "-";
029
030    public ExportEngines() {
031        // nothing to do
032    }
033
034    /**
035     * Store the all of the operation Engine objects in the default place,
036     * including making a backup if needed
037     */
038    public void writeOperationsEngineFile() {
039        makeBackupFile(defaultOperationsFilename());
040        try {
041            if (!checkFile(defaultOperationsFilename())) {
042                // The file does not exist, create it before writing
043                java.io.File file = new java.io.File(defaultOperationsFilename());
044                java.io.File parentDir = file.getParentFile();
045                if (!parentDir.exists()) {
046                    if (!parentDir.mkdir()) {
047                        log.error("Directory wasn't created");
048                    }
049                }
050                if (file.createNewFile()) {
051                    log.debug("File created");
052                }
053            }
054            writeFile(defaultOperationsFilename());
055        } catch (IOException e) {
056            log.error("Exception while writing the new CSV operations file, may not be complete", e);
057        }
058    }
059
060    public void writeFile(String name) {
061        log.debug("writeFile {}", name);
062        // This is taken in large part from "Java and XML" page 368
063        File file = findFile(name);
064        if (file == null) {
065            file = new File(name);
066        }
067
068        try (CSVPrinter fileOut = new CSVPrinter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)),
069                CSVFormat.DEFAULT)) {
070
071            EngineManager manager = InstanceManager.getDefault(EngineManager.class);
072            List<Engine> engineList = manager.getByNumberList();
073
074            // create header
075            fileOut.printRecord(Bundle.getMessage("Number"),
076                    Bundle.getMessage("Road"),
077                    Bundle.getMessage("Model"),
078                    Bundle.getMessage("Length"),
079                    Bundle.getMessage("Owner"),
080                    Bundle.getMessage("Built"),
081                    Bundle.getMessage("Location"),
082                    LOCATION_TRACK_SEPARATOR,
083                    Bundle.getMessage("Track"),
084                    Bundle.getMessage("Consist"),
085                    Bundle.getMessage("Moves"),
086                    Bundle.getMessage("Last"),
087                    Setup.getValueLabel(),
088                    Bundle.getMessage("HP"),
089                    Bundle.getMessage("WeightTons"),
090                    Bundle.getMessage("Type"),
091                    Bundle.getMessage("Comment"),
092                    Bundle.getMessage("Miscellaneous"));
093
094            // store engine number, road, model, length, owner, built date, location - track
095            for (Engine engine : engineList) {
096                fileOut.printRecord(engine.getNumber(),
097                        engine.getRoadName(),
098                        engine.getModel(),
099                        engine.getLength(),
100                        engine.getOwnerName(),
101                        engine.getBuilt(),
102                        engine.getLocationName(),
103                        LOCATION_TRACK_SEPARATOR,
104                        engine.getTrackName(),
105                        engine.getConsistName(),
106                        engine.getMoves(),
107                        engine.getLastDate(),
108                        engine.getValue(),
109                        engine.getHp(),
110                        engine.getWeightTons(),
111                        engine.getTypeName(),
112                        engine.getComment(),
113                        engine.isOutOfService() ? Bundle.getMessage("OutOfService") : "");
114            }
115            fileOut.flush();
116            fileOut.close();
117            log.info("Exported {} engines to file {}", engineList.size(), defaultOperationsFilename());
118            JmriJOptionPane.showMessageDialog(null, Bundle.getMessage("ExportedEnginesToFile",
119                    engineList.size(), defaultOperationsFilename()), Bundle.getMessage("ExportComplete"),
120                    JmriJOptionPane.INFORMATION_MESSAGE);
121        } catch (IOException e) {
122            log.error("Can not open export engines CSV file: {}", file.getName());
123            JmriJOptionPane.showMessageDialog(null, Bundle.getMessage("ExportedEnginesToFile",
124                    0, defaultOperationsFilename()), Bundle.getMessage("ExportFailed"),
125                    JmriJOptionPane.ERROR_MESSAGE);
126        }
127    }
128
129    // Operation files always use the same directory
130    public static String defaultOperationsFilename() {
131        return OperationsSetupXml.getFileLocation()
132                + OperationsSetupXml.getOperationsDirectoryName()
133                + File.separator
134                + getOperationsFileName();
135    }
136
137    public static void setOperationsFileName(String name) {
138        operationsFileName = name;
139    }
140
141    public static String getOperationsFileName() {
142        return operationsFileName;
143    }
144
145    private static String operationsFileName = "ExportOperationsEngineRoster.csv"; // NOI18N
146
147    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ExportEngines.class);
148
149}