package hirondelle.stocks.export;
import javax.swing.*;
import java.awt.event.*;
import java.io.File;
import java.util.logging.*;
import hirondelle.stocks.portfolio.PortfolioDAO;
import hirondelle.stocks.util.Args;
import hirondelle.stocks.util.ui.UiUtil;
import hirondelle.stocks.util.Util;
public final class ExportAction extends AbstractAction {
public ExportAction(JFrame aFrame) {
super("Export...", UiUtil.getEmptyIcon());
Args.checkForNull(aFrame);
fFrame = aFrame;
putValue(SHORT_DESCRIPTION, "Save all stored Portfolios as a single text file");
putValue(
LONG_DESCRIPTION,
"Save all stored Portfolios as an XML file, suitable as input to the Import command."
);
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_E) );
}
@Override public void actionPerformed (ActionEvent event) {
fLogger.info("Exporting Portfolios to a single text file.");
JFileChooser chooser = new JFileChooser(fDirOfInterest);
chooser.setDialogTitle("Export All Portfolios");
chooser.setApproveButtonToolTipText("Save all Portfolios to single text file");
int choice = chooser.showDialog(fFrame, "Export");
if (choice != JFileChooser.APPROVE_OPTION) {
fLogger.fine("No file selection made");
return;
}
File file = chooser.getSelectedFile();
fDirOfInterest = file.getParentFile();
if ( file.exists() && !file.canWrite() ){
fLogger.fine("file does not have write access: " + file);
JOptionPane.showMessageDialog(
fFrame, fNO_WRITE_MESSAGE,
UiUtil.getDialogTitle("Invalid Export File"), JOptionPane.ERROR_MESSAGE
);
return;
}
if ( file.exists() && file.canWrite() ) {
fLogger.fine( "File exists and may be overwritten: " + file);
if ( ! isOverwriteConfirmed(file) ) return;
}
fLogger.fine("Attempting to write to export file");
PortfolioDAO dao = new PortfolioDAO();
dao.exportXML(file);
}
private JFrame fFrame;
private static File fDirOfInterest;
private static final Object[] fNO_WRITE_MESSAGE = {
"Read-only file.",
"The file you have selected is read-only, and cannot be changed.",
"Please select a new file."
};
private static final Logger fLogger = Util.getLogger(ExportAction.class);
private boolean isOverwriteConfirmed(File aFile){
String title = UiUtil.getDialogTitle("Confirm Overwrite");
Object[] message = {
"This file already exists.",
"Do you wish to overwrite " + aFile.getName() + " ?"
};
int result = JOptionPane.showConfirmDialog(
fFrame, message, title, JOptionPane.YES_NO_OPTION
);
return (result == JOptionPane.YES_OPTION ? true : false);
}
}