001    package net.sourceforge.mp3dings;
002    
003    /*
004     *  Mp3dings - manage mp3 meta-information
005     *  Copyright (C) 2003 Moritz Ringler
006     *  $Id: Application.java 98 2007-11-01 10:17:50Z ringler $
007     *
008     *  This program is free software; you can redistribute it and/or
009     *  modify it under the terms of the GNU General Public License
010     *  as published by the Free Software Foundation; either version 2
011     *  of the License, or (at your option) any later version.
012     *
013     *  This program is distributed in the hope that it will be useful,
014     *  but WITHOUT ANY WARRANTY; without even the implied warranty of
015     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
016     *  GNU General Public License for more details.
017     *
018     *  You should have received a copy of the GNU General Public License
019     *  along with this program; if not, write to the Free Software
020     *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
021     */
022    import java.io.BufferedInputStream;
023    import java.io.BufferedOutputStream;
024    import java.io.File;
025    import java.io.FileInputStream;
026    import java.io.FileOutputStream;
027    import java.io.IOException;
028    import java.io.InputStream;
029    import java.io.OutputStream;
030    import java.util.Enumeration;
031    import java.util.HashMap;
032    import java.util.Iterator;
033    import java.util.Locale;
034    import java.util.Map;
035    import java.util.Set;
036    import java.util.TreeSet;
037    import java.util.logging.Level;
038    import java.util.logging.Logger;
039    import java.util.prefs.BackingStoreException;
040    import java.util.prefs.InvalidPreferencesFormatException;
041    import java.util.prefs.Preferences;
042    import java.util.zip.ZipEntry;
043    import java.util.zip.ZipFile;
044    import java.util.zip.ZipOutputStream;
045    import javax.swing.SwingUtilities;
046    import de.mospace.lang.DefaultClassLoaderProvider;
047    import de.mospace.swing.LookAndFeelMenu;
048    import net.sourceforge.mp3dings.filter.FilterSetCustomizer;
049    import net.sourceforge.mp3dings.filter.NumericFilter;
050    import net.sourceforge.mp3dings.preferences.FilteredField;
051    
052    /**
053     * The main class of the mp3dings program. It provides the
054     * <code>main(String[] args)</code>
055     * method that starts mp3dings as well as methods to access some components and
056     * services used by all of the application.
057     *
058     * @author Moritz Ringler
059     * @version $Revision: 98 $ ($Date: 2007-11-01 11:17:50 +0100 (Do, 01 Nov 2007) $)
060     */
061    public final class Application extends DefaultClassLoaderProvider {
062        private static final Logger logger = Logger.getLogger(Application.class.getPackage().getName());
063        /** Frame making up the graphical user interface of the application */
064        protected MainFrame mainFrame;
065    
066    
067        /** Starts a new mp3dings application. <em>It has not been tested
068        * whether creating several instances of this class
069        * in the same JVM is safe.</em>
070        */
071        public Application() {
072            super();
073            System.setSecurityManager(null);
074    
075            /*
076             *  register libraries
077             */
078            File repositoryRootLib = null;
079            try{
080                repositoryRootLib = new File(
081                    getRepositoryRootDir(Application.class), "lib");
082            } catch (Exception ignore){
083            }
084            Set libSet = new TreeSet();
085            libSet.add(new File(Globals.getDir("LIB")));
086            libSet.add(new File(System.getProperty("user.dir"), "lib"));
087            if (repositoryRootLib != null && !isTemporary(repositoryRootLib)) {
088                libSet.add(repositoryRootLib);
089            }
090            String s = Globals.getPrefNode().get("LibDir", null);
091            if (s != null) {
092                libSet.add(new File(s));
093            }
094            registerLibraryDirectories((File[]) libSet.toArray(new File[0]));
095    
096            boolean success = false;
097            try{
098                success = LookAndFeelMenu.setLookAndFeel(Globals.getPrefNode(), getClassLoader());
099            } catch (Throwable ex){
100    
101            }
102            if(! success){
103                Globals.getPrefNode().remove("LookAndFeelClass");
104                logger.severe("Resetting to default look and feel.");
105                logger.severe("Please restart!");
106                System.exit(1);
107            }
108    
109            /*
110             *  Check if user's default locale is implemented
111             *  if not switch to application default.
112             */
113            boolean defaultLocaleImplemented = false;
114            Locale[] lc = getImplementedLocales();
115            //assert lc.length > 0;
116            String defaultLanguage = Globals.getPrefNode().get("Language",
117                    Locale.getDefault().getLanguage());
118            for (int i = 0; i < lc.length; i++) {
119                if (lc[i].getLanguage().equals(defaultLanguage)) {
120                    defaultLocaleImplemented = true;
121                    Locale.setDefault(lc[i]);
122                    break;
123                }
124            }
125            if (!defaultLocaleImplemented) {
126                Locale l = Locale.getDefault();
127                Locale.setDefault(lc[0]);
128                logger.info("System default language (" + l.getDisplayLanguage() +
129                        ") is not implemented in mp3dings. Using " + lc[0].getDisplayLanguage() + ".");
130            }
131            //System.setProperty("java.net.useSystemProxies", "true");
132    
133            mainFrame = new MainFrame(this);
134            mainFrame.setVisible(true);
135            setStatus(Globals.getString("MAIN_STATUS_BAR_STARTUP_TEXT"));
136        }
137    
138    
139        /**
140        * Main method invoked to start the application. You can optionally specify
141        * zip files with settings to import before the application is started.
142        * This is used mainly in the installation procedure, but can also
143        * be used as a primitive profile mechanism. Note that instances of
144        * mp3dings that are already running will also be affected.<p>
145        * <em>It has not
146        * been tested whether several instances of mp3dings can safely run
147        * inside the same JVM.</em>
148        *
149        * @param argv one or more zip files with mp3dings settings
150        */
151        public static void main(String[] argv) {
152            System.setProperty("apple.laf.useScreenMenuBar", "true");
153            for (int i = 0; i < argv.length; i++) {
154                importSettings(argv[i]);
155            }
156            SwingUtilities.invokeLater(
157            new Runnable() {
158                public void run() {
159                    new Application();
160                }
161            });
162        }
163    
164    
165        /**
166         * Displays the specified string in the status bar of the application
167         * window.
168         *
169         * @param status The new status value
170         * @see de.mospace.swing.StatusBar#setStatus(String status)
171         */
172        protected void setStatus(String status) {
173            mainFrame.setStatus(status);
174        }
175    
176    
177        /**
178         * Displays the specified string in the status bar of the application
179         * window and clears after the specified time.
180         *
181         * @param status The new status value
182         * @param timeout The new status value
183         * @see de.mospace.swing.StatusBar#setStatus(String status, int timeout)
184         */
185        protected void setStatus(String status, int timeout) {
186            mainFrame.setStatus(status, timeout);
187        }
188    
189    
190        /**
191         * Returns the locales that are currently supported by mp3dings. *
192         *
193         * @return the implemented locales
194         */
195        protected static Locale[] getImplementedLocales() {
196            return new Locale[]{
197                    new Locale("en", "US"),
198                    new Locale("de", "DE")
199                    };
200        }
201    
202    
203        /**
204         * Gets the mainFrame attribute of the Application object
205         *
206         * @return The mainFrame value
207         */
208        public MainFrame getMainFrame() {
209            return mainFrame;
210        }
211    
212    
213        /**
214        * Exits the application cleanly.
215        *
216        * @param code an exit code
217        *
218        * @see java.lang.System#exit(int)
219        */
220        public void exit(int code) {
221            mainFrame.setVisible(false);
222            mainFrame.goingToExit();
223            System.exit(code);
224        }
225    
226    
227        /** Installs default filters for a new mp3dings installation or user. */
228        static void createDefaultFilters() {
229            /*
230             *  create default filters
231             */
232            NumericFilter yearFilter = new NumericFilter(1900, 2050, true);
233            yearFilter.setName(Field.YEAR.longname() + " 1900-2050");
234            NumericFilter trackFilter = new NumericFilter(0, 31, true);
235            trackFilter.setName(Field.TRACK.longname() + " 0-31");
236    
237            /*
238             *  save them and provide them with valid IDs
239             */
240            boolean saved = true;
241            try {
242                FilterSetCustomizer fsc = new FilterSetCustomizer();
243                fsc.addBean(yearFilter);
244                fsc.addBean(trackFilter);
245                fsc.save();
246            } catch (Exception ex) {
247                logger.severe("Error saving default filters.");
248                Globals.logStackTrace(logger, Level.SEVERE, ex);
249                saved = false;
250            }
251    
252            /*
253             *  associate them with data/track and data/year
254             */
255            if (saved) {
256                FilteredField field = new FilteredField(Field.YEAR);
257                field.getFilters().add(yearFilter);
258                //hard coded pref node is not very nice...
259                Preferences p = Globals.getPrefNode().node("data").node("filters");
260                field.save(p);
261                field = new FilteredField(Field.TRACK);
262                field.getFilters().add(trackFilter);
263                field.save(p);
264            }
265        }
266    
267    
268        private static void importSettings(String arg) {
269            if (!arg.endsWith(".zip")) {
270                logger.warning("[importSettings] Warning: " + arg + " is not a zip file and will not be imported.");
271                return;
272            }
273            File settings = new File(arg);
274            if (!settings.isFile()) {
275                logger.warning("[importSettings] Warning: " + arg + " is not an existing zip archive and will not be imported.");
276                return;
277            }
278            try {
279                importSettings(settings);
280                logger.info(Globals.getMessage("IMPORT_SETTINGS_SUCCESS",
281                        settings.getName()));
282            } catch (Exception ex) {
283                logger.severe("Error importing settings: " + ex.getMessage());
284            }
285        }
286    
287    
288        /**
289         * Description of the Method
290         *
291         * @param settings Description of the Parameter
292         * @exception IOException Description of the Exception
293         */
294        public static void importSettings(File settings) throws IOException, InvalidPreferencesFormatException {
295            ZipFile zippi = null;
296            OutputStream out = null;
297            try {
298                int count;
299                int BUFFER = 2048;
300                byte data[] = new byte[BUFFER];
301    
302                zippi = new ZipFile(settings);
303    
304                /*
305                 *  read prefs
306                 */
307                ZipEntry entry;
308                entry = zippi.getEntry("mp3dings-prefs.xml");
309                if (entry == null) {
310                    throw new IOException(settings.getName() + " in not an mp3dings settings zip archive.");
311                }
312                InputStream in = zippi.getInputStream(entry);
313                Preferences.importPreferences(in);
314                in.close();
315    
316                /*
317                 *  read filters
318                 */
319                Enumeration entries = zippi.entries();
320                Map dirMap = new HashMap();
321                dirMap.put("filters", Globals.getDir("FILTERS"));
322                dirMap.put("beans", Globals.getDir("BEANS"));
323                dirMap.put("patterns", Globals.getDir("HOME") +
324                        File.separator + "patterns");
325                Iterator it = dirMap.keySet().iterator();
326                while (it.hasNext()) {
327                    String zipdir = (String) it.next();
328                    String dir = (String) dirMap.get(zipdir);
329                    zipdir += "/";
330                    File targetDirectory = new File(dir);
331                    targetDirectory.mkdirs();
332                    String fname;
333                    while (entries.hasMoreElements()) {
334                        entry = (ZipEntry) entries.nextElement();
335                        fname = entry.getName();
336                        if (fname.startsWith(zipdir)) {
337                            out = new FileOutputStream(new File(targetDirectory,
338                                    fname.replaceFirst(zipdir, "")));
339                            out = new BufferedOutputStream(out);
340                            in = zippi.getInputStream(entry);
341                            while ((count = in.read(data, 0, BUFFER)) != -1) {
342                                out.write(data, 0, count);
343                            }
344                            out.close();
345                            out = null;
346                            in.close();
347                        }
348                    }
349                }
350            } finally {
351                try {
352                    if (zippi != null) {
353                        zippi.close();
354                    }
355                } catch (IOException ignore) {}
356                try {
357                    if (out != null) {
358                        out.close();
359                    }
360                } catch (IOException ignore) {}
361            }
362        }
363    
364    
365        /**
366         * Saves the current mp3dings settings to the specified file.
367         *
368         * @param settings the file to save the settings to
369         */
370        public static void exportSettings(File settings) throws IOException, BackingStoreException {
371            OutputStream out = null;
372            InputStream in = null;
373            try {
374                int count;
375                int BUFFER = 2048;
376                byte data[] = new byte[BUFFER];
377    
378                /*
379                 *  create zip file
380                 */
381                out = new FileOutputStream(settings);
382                out = new BufferedOutputStream(out, BUFFER);
383                ZipOutputStream zippo = new ZipOutputStream(out);
384                out = zippo;
385    
386                /*
387                 *  save prefs
388                 */
389                zippo.putNextEntry(new ZipEntry("mp3dings-prefs.xml"));
390                Globals.getPrefNode().exportSubtree(zippo);
391                zippo.closeEntry();
392    
393                /*
394                 *  save filters
395                 */
396                Map dirMap = new HashMap();
397                dirMap.put("filters", Globals.getDir("FILTERS"));
398                dirMap.put("beans", Globals.getDir("BEANS"));
399                dirMap.put("patterns", Globals.getDir("HOME") +
400                        File.separator + "patterns");
401                Iterator it = dirMap.keySet().iterator();
402                while (it.hasNext()) {
403                    String zipdir = (String) it.next();
404                    String dir = (String) dirMap.get(zipdir);
405                    File beanDir = new File(dir);
406                    if (beanDir.isDirectory()) {
407                        File[] beans = beanDir.listFiles();
408                        for (int i = 0; i < beans.length; i++) {
409                            if (!beans[i].isFile()) {
410                                continue;
411                            }
412                            in = new FileInputStream(beans[i]);
413                            in = new BufferedInputStream(in);
414                            zippo.putNextEntry(new ZipEntry(zipdir + "/" + beans[i].getName()));
415                            while ((count = in.read(data, 0, BUFFER)) != -1) {
416                                zippo.write(data, 0, count);
417                            }
418                            zippo.closeEntry();
419                            in.close();
420                            in = null;
421                        }
422                    }
423                    // } else if (beanDir.isFile()){
424                    // in = new FileInputStream(beanDir);
425                    // in = new BufferedInputStream(in);
426                    // zippo.putNextEntry(new ZipEntry(beanDir.getName()));
427                    // while ((count = in.read(data, 0, BUFFER)) != -1) {
428                    // zippo.write(data, 0, count);
429                    // }
430                    // zippo.closeEntry();
431                    // in.close();
432                    // in = null;
433                    // }
434                }
435                out.close();
436                out = null;
437            } finally {
438                if (out != null) {
439                    try {
440                        out.close();
441                    } catch (IOException ignore) {}
442                }
443                if (in != null) {
444                    try {
445                        in.close();
446                    } catch (IOException ignore) {}
447                }
448            }
449            //end of finally
450        }
451    
452    }