001    package net.sourceforge.mp3dings.export;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2003 Moritz Ringler
005     * $Id: DatabaseConfigPopup.java 143 2008-05-14 07:18:25Z ringler $
006     *
007     * This program is free software; you can redistribute it and/or
008     * modify it under the terms of the GNU General Public License
009     * as published by the Free Software Foundation; either version 2
010     * of the License, or (at your option) any later version.
011     *
012     * This program is distributed in the hope that it will be useful,
013     * but WITHOUT ANY WARRANTY; without even the implied warranty of
014     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015     * GNU General Public License for more details.
016     *
017     * You should have received a copy of the GNU General Public License
018     * along with this program; if not, write to the Free Software
019     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
020     */
021    
022    import java.awt.event.ActionEvent;
023    import java.awt.event.ActionListener;
024    import java.io.File;
025    import java.io.FileOutputStream;
026    import java.io.IOException;
027    import java.util.Properties;
028    import java.util.logging.Logger;
029    import javax.swing.JFileChooser;
030    import javax.swing.JMenu;
031    import javax.swing.JMenuItem;
032    import javax.swing.filechooser.FileFilter;
033    import net.sourceforge.mp3dings.Globals;
034    import net.sourceforge.mp3dings.MainFrame;
035    import net.sourceforge.mp3dings.Mp3dingsTableModel;
036    import net.sourceforge.mp3dings.utils.DialogExceptionHandler;
037    
038    /**A popup menu for configuring a {@link DatabaseConnection JDBC database
039     * connection}. At the moment, it consists of a menu item carrying the name
040     * of the current database configuration (if any), a menu item that
041     * allows to edit or create a database configuration,
042     * and a menu item that loads a database configuration from a file.
043     *
044     * @author Moritz Ringler
045     * @version $Revision: 143 $ ($Date: 2008-05-14 09:18:25 +0200 (Mi, 14 Mai 2008) $)
046     */
047    public class DatabaseConfigPopup extends JMenu{
048        private static final Logger logger = Logger.getLogger(DatabaseConfigPopup.class.getPackage().getName());
049        private final Trigger trigger;
050        private final JFileChooser chooser;
051    
052        /** The constructor argument for a database export menu. */
053        public final static int EXPORT = 0;
054    
055        /** The constructor argument for a database import menu. */
056        public final static int IMPORT = 1;
057        private final String prefNode;
058    
059        /** The action command of the action event that is fired by the menu item
060        * carrying the name of the current configuration.
061        *
062        * @see java.awt.event.ActionEvent#getActionCommand
063        */
064        public final static String ACTION_COMMAND =
065            "net.sourceforge.mp3dings.export.DatabaseConfigPopup.ACTION_COMMAND";
066    
067        /** The action command of the action event that is fired when we have
068        * a new database configuration.
069        *
070        * @see java.awt.event.ActionEvent#getActionCommand
071        */
072        public final static String CONFIG_CHANGED =
073            "net.sourceforge.mp3dings.export.DatabaseConfigPopup.CONFIG_CHANGED";
074    
075        /** Creates a new DatabaseConfigPopup.
076        * @param trig the trigger for this popupmenu
077        * @param mode one of EXPORT or IMPORT
078        * @see Trigger
079        * @throws IllegalArgumentException if mode is neither EXPORT nor IMPORT
080        */
081        public DatabaseConfigPopup(Trigger trig, int mode){
082            final int mmode = mode;
083            prefNode = (mode == EXPORT)? DatabaseConnection.PREF_EXPORT : DatabaseConnection.PREF_IMPORT;
084            trigger = trig;
085            JMenuItem jmi = new JMenuItem(Globals.getString("DB_CONFIG_EDIT"));
086    
087            String currentConfig = Globals.getPrefNode().get(prefNode, ".");
088            File config =  new File(currentConfig);
089            chooser = new JFileChooser(config);
090            FileFilter ff = new FileFilter(){
091                public boolean accept(File f){
092                    return f.isDirectory() || f.getName().endsWith(".properties");
093                }
094    
095                public String getDescription(){
096                    return "*.properties";
097                }
098            };
099            chooser.setFileFilter(ff);
100            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
101            chooser.setMultiSelectionEnabled(false);
102    
103            jmi.addActionListener(new ActionListener(){
104                    public void actionPerformed(ActionEvent e){
105                        Properties p = null;
106                        try{
107                            switch(mmode){
108                                case EXPORT:
109                                    p = DatabaseExporter.loadConfig();
110                                    p = DatabaseExporter.editConfig(
111                                        trigger.getOwner(),
112                                        p,
113                                        trigger.getActiveModel().getFields(),
114                                        null
115                                    );
116                                    break;
117                                case IMPORT:
118                                    p = DatabaseImporter.loadConfig();
119                                    p = DatabaseImporter.editConfig(
120                                            trigger.getOwner(), p,
121                                            trigger.getActiveModel().getFields(),
122                                            null);
123                                    break;
124                                default:
125                                    throw new IllegalArgumentException("Mode must be one of EXPORT, IMPORT.");
126                            }
127                        } catch (Exception ex){
128                            ex.printStackTrace();
129                            p = null;
130                        }
131                        if(p != null){
132                            int result = chooser.showSaveDialog(trigger.getOwner());
133                            if(result == JFileChooser.APPROVE_OPTION && chooser.getSelectedFile() != null){
134                                FileOutputStream fos = null;
135                                File prop = chooser.getSelectedFile();
136                                try{
137                                    fos = new FileOutputStream(prop);
138                                    Properties ps = (Properties) p.clone();
139                                    ps.remove(DatabaseConnection.P_PASSWORD);
140                                    ps.store(fos, "mp3dings<->jdbc configuration");
141                                } catch (IOException ex){
142                                    (new DialogExceptionHandler(Globals.getString("ERROR"), trigger.getOwner())).handleException(ex);
143                                    return;
144                                } finally {
145                                    if(fos != null){
146                                        try{
147                                            fos.close();
148                                        } catch (IOException ex){
149                                            logger.warning("Cannot close file " + prop);
150                                            logger.warning(ex.toString());
151                                        }
152                                    }
153                                }
154                                loadConfigAndFireActionPerformed(prop);
155                            }
156                        }
157                    }
158            });
159            add(jmi);
160            jmi = new JMenuItem(Globals.getString("DB_CONFIG_LOAD"));
161            jmi.addActionListener(new ActionListener(){
162                public void actionPerformed(ActionEvent e){
163                    int result = chooser.showOpenDialog(trigger.getOwner());
164                    if(result == JFileChooser.APPROVE_OPTION && chooser.getSelectedFile() != null){
165                        loadConfigAndFireActionPerformed(chooser.getSelectedFile());
166                    }
167                }
168            });
169            add(jmi);
170            updateActionTriggerItem(Globals.getPrefNode().get(prefNode, null));
171        }
172    
173    
174        private void loadConfigAndFireActionPerformed(File properties){
175            String configPath = properties.getAbsolutePath();
176            Globals.getPrefNode().put(prefNode, configPath);
177            JMenuItem actionTrigger = updateActionTriggerItem(configPath);
178            ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, CONFIG_CHANGED);
179            trigger.actionPerformed(e);
180            if(actionTrigger != null){
181                actionTrigger.doClick();
182            }
183        }
184    
185        private JMenuItem updateActionTriggerItem(String configPath){
186            JMenuItem jmi = null;
187            if(configPath != null){
188                File config = new File(configPath);
189                if(config.isFile()){
190                    String title = config.getName().replaceFirst("\\.properties$","");
191                    if(getItemCount() == 3){
192                        jmi = getItem(0);
193                        jmi.setText(title);
194                    } else {
195                        jmi = new JMenuItem(title);
196                        jmi.setActionCommand(ACTION_COMMAND);
197                        jmi.addActionListener(trigger);
198                        insert(jmi, 0);
199                    }
200                }
201            }
202            return jmi;
203        }
204    
205        /** Objects that want to trigger a DatabaseConfigPopup must comply to this
206        * interface. In response to user actions the trigger will receive
207        * action events that have their action commands set to
208        * {@link DatabaseConfigPopup#ACTION_COMMAND} or
209        * {@link DatabaseConfigPopup#CONFIG_CHANGED}.
210        *
211        * @see DatabaseConfigPopup#DatabaseConfigPopup DatabaseConfigPopup(Trigger, int)
212        */
213        public static interface Trigger extends ActionListener{
214            public MainFrame getOwner();
215            public Mp3dingsTableModel getActiveModel();
216        }
217    }