001    package net.sourceforge.mp3dings.export;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2003 Moritz Ringler
005     * $Id: AbstractExporter.java 103 2007-11-05 11:31:35Z 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.io.File;
023    import java.io.FileOutputStream;
024    import java.io.IOException;
025    import java.io.OutputStreamWriter;
026    import java.io.Serializable;
027    import java.nio.charset.Charset;
028    import java.util.HashMap;
029    import java.util.Map;
030    import java.util.logging.Logger;
031    import java.util.prefs.Preferences;
032    import javax.swing.JFileChooser;
033    import javax.swing.filechooser.FileFilter;
034    import net.sourceforge.mp3dings.Globals;
035    
036    /**An {@link Exporter} that exports a file composed of a header section,
037     * a main section with one block per record and a footer section.
038     * @author Moritz Ringler
039     * @version $Revision: 103 $ ($Date: 2007-11-05 12:31:35 +0100 (Mo, 05 Nov 2007) $)
040     */
041    public abstract class AbstractExporter implements Exporter, Serializable{
042        private static final Logger logger = Logger.getLogger(AbstractExporter.class.getPackage().getName());
043        static final long serialVersionUID = -3104633648349382257L;
044    
045        private final static Object[] NULL_KEYS = new Object[]{};
046        private transient Object[] headerDataKeys = NULL_KEYS;
047        private transient Object[] footerDataKeys = NULL_KEYS;
048        private transient Object[] blockDataKeys = NULL_KEYS;
049        private boolean fileFallback = true;
050        private transient int numEntries = 0;
051        private Charset charset = Charset.forName("ISO-8859-1");
052        private transient Map headerdata;
053        private transient Map footerdata;
054        private static String[] implementations;
055    
056        /** Sets the charset that will be used to encode the strings for exporting.
057         * The default is "ISO-8859-1".
058         * @param enc The name of the charset; may be either a canonical name or an alias
059         * @see net.sourceforge.mp3dings.export.Exporter#setEncoding(String enc)
060         */
061        public boolean setEncoding(String enc){
062            try {
063                charset = Charset.forName(enc);
064            } catch (Exception ex){
065                return false;
066            }
067            return true;
068        }
069    
070        /**Returns all keys used by this exporter in a single array. The keys will
071        * usually be the required {@link net.sourceforge.mp3dings.Field Fields}.
072         * @return An Object array containing all keys (header, block and footer)
073         * @see net.sourceforge.mp3dings.export.Exporter#getKeys()
074         * @see #getHeaderKeys()
075         * @see #getBlockKeys()
076         * @see #getFooterKeys()
077         */
078        public Object[] getKeys(){
079            int i = 0;
080            Object[] fields = new Object[headerDataKeys.length +
081                    blockDataKeys.length +
082                    footerDataKeys.length];
083            System.arraycopy(headerDataKeys,0,fields,i,headerDataKeys.length);
084            i += headerDataKeys.length;
085            System.arraycopy(blockDataKeys,0,fields,i,blockDataKeys.length);
086            i += blockDataKeys.length;
087            System.arraycopy(footerDataKeys,0,fields,i,footerDataKeys.length);
088            return fields;
089        }
090    
091        /**Sets the keys for a specific implementation. Use null for
092         * no keys.
093         * @param headerKeys the fields for the header
094         * @param blockKeys the fields for the main section
095         * @param footerKeys the fields for the footer
096         *
097         * @see #getKeys()
098         */
099        public void setKeys(Object[] headerKeys, Object[] blockKeys, Object[] footerKeys){
100            headerDataKeys = (headerKeys != null)? headerKeys : NULL_KEYS;
101            blockDataKeys  = (blockKeys  != null)? blockKeys  : NULL_KEYS;
102            footerDataKeys = (footerKeys != null)? footerKeys : NULL_KEYS;
103        }
104    
105        /**Sets the header data that {@link #getHeader()} will use to generate
106         * the header section. Changes to the specified Map will result
107         * in changes in the exported data.
108         * @param hd Map containing the header data. The keys whose values
109         * should be populated can be retrieved using {@link #getHeaderKeys()}.
110         */
111        public void setHeaderData(Map hd){
112            headerdata = hd;
113        }
114    
115        /** Returns the current header data.
116         * @return the Map passed in by the last call to
117         * {@link #setHeaderData(Map )}
118         */
119        public Map getHeaderData(){
120            return headerdata;
121        }
122    
123        /**Sets the footer data that {@link #getFooter(int)} will use to generate
124         * the footer section
125         * @param fd Map containing the footer data. Its keys can be
126         * retrieved using {@link #getFooterKeys()}.
127         */
128        public void setFooterData(Map fd){
129            footerdata = fd;
130        }
131    
132        /** Returns the current footer data.
133         * @return the data passed in by the last call to
134         * {@link #setFooterData(Map )}
135         */
136        public Map getFooterData(){
137            return footerdata;
138        }
139    
140        /**Gets the number of datasets in the last call to
141         * {@link #export(Object[] fields, Object[][] data)}
142         */
143        public int getNumberOfEntries(){
144            return numEntries;
145        }
146    
147        /**Returns the header keys used by this exporter. The keys will
148         * usually be the required {@link net.sourceforge.mp3dings.Field Fields}.
149         * @return An Object array containing all header keys
150         * @see #getKeys()
151         *
152         * @see #setHeaderData(Map )**/
153        public Object[] getHeaderKeys(){
154            Object[] value = new Object[headerDataKeys.length];
155            System.arraycopy(headerDataKeys,0,value,0,value.length);
156            return value;
157        }
158    
159        /**Returns the block keys used by this exporter. The keys will
160         * usually be the required {@link net.sourceforge.mp3dings.Field Fields}.
161         * @return An Object array containing all block keys
162         * @see #getKeys()
163         */
164        public Object[] getBlockKeys(){
165            Object[] value = new Object[blockDataKeys.length];
166            System.arraycopy(blockDataKeys,0,value,0,value.length);
167            return value;
168        }
169    
170        /**Returns the footer keys used by this exporter. The keys will
171         * usually be the required {@link net.sourceforge.mp3dings.Field Fields}.
172         * @return An Object array containing all footer keys
173         * @see #getKeys()
174         */
175        public Object[] getFooterKeys(){
176            Object[] value = new Object[footerDataKeys.length];
177            System.arraycopy(footerDataKeys,0,value,0,value.length);
178            return value;
179        }
180    
181        /** Equivalent to <code>export(field, data, null)</code>.
182        * @see #export(Object[], Object[][], StringBuffer)
183        */
184        public int export(Object[] keys, Object[][] data)
185                throws ExportException{
186            return export(keys, data, null);
187        }
188    
189        /**Opens a {@link javax.swing.JFileChooser JFileChooser} using the file
190         * filter returned by {@link #getFileFilter()} and exports the
191         * current data to the selected file. The exported file is composed of
192         * <ol>
193         *      <li>a single return value of {@link #getHeader()}</li>
194         *      <li>one block ({@link #getBlock(int, Map)}) for each
195         *          dataset in the data array</li>
196         *      <li>a single return value of {@link #getFooter(int)}.</li>
197         * </ol>
198         * @param keys an array containing the fields the data contains.
199         * @param data a 2D array of block data. The first index designates
200         *        the number of the dataset, the second index designates the
201         *        data field. data[i][j] is the value of field keys[j] for
202         *        the ith dataset.
203         * @param filename name of the file to export to. If null or empty the user
204         *        will be prompted for a value. A non-null object will hold the
205         *        finally used filename after a succesfull call, and null after
206         *        an unsuccessful call.
207         * @return the number of successfully exported rows
208         */
209        public int export(Object[] keys, Object[][] data, StringBuffer filename)
210                throws ExportException{
211            /* return if nothing to do */
212            if (keys == null || data == null || data.length == 0){
213                return 0;
214            }
215            /* get export path from preferences and pick output file */
216            Preferences pref = Globals.getPrefNode().node("export");
217            if (filename == null || filename.toString().equals("")){
218                JFileChooser fc = new JFileChooser(pref.get("ExportPath",null));
219                fc.setFileFilter(getFileFilter());
220                if(fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
221                    File output = fc.getSelectedFile();
222                    if (filename == null){
223                        filename = new StringBuffer(output.getAbsolutePath());
224                    } else {
225                        //assert filename.toString().equals("");
226                        filename.append(output.getAbsolutePath());
227                    }
228                } else {
229                    return 0;
230                }
231            }
232            /* force extension */
233            if(!filename.toString().endsWith(getExtension())){
234                filename.append(getExtension());
235            }
236            /* save export path to preferences for next call */
237            pref.put("ExportPath",filename.toString());
238            /* generate minimal field array */
239            numEntries = data.length;
240            int n = Math.min(keys.length, data[0].length);
241            Object[] fields = new Object[n];
242            System.arraycopy(keys,0,fields,0,n);
243            /* set default encoding (UTF-8) */
244            if (charset == null){
245                setEncoding("UTF-8");
246            }
247            /* open output file for writing */
248            OutputStreamWriter fw = null;
249            try{
250                fw = new OutputStreamWriter(
251                        new FileOutputStream(new File(filename.toString())),
252                        charset);
253                /* generate and write header */
254                String s = getHeader();
255                fw.write(s);
256                /* generate block data Maps and write block data */
257                Map bd = new HashMap();
258                for (int i=0; i<numEntries; i++){
259                    for (int j=0; j<n; j++){
260                        bd.put(fields[j], data[i][j]);
261                    }
262                    s = getBlock(i,bd);
263                    fw.write(s);
264                }
265                /* generate and write footer */
266                s = getFooter(numEntries);
267                fw.write(s);
268            } catch (IOException ex){
269                throw new ExportException(ex);
270            } finally {
271                try{
272                    /* close output file */
273                    if(fw != null){
274                        fw.close();
275                    }
276                } catch (IOException ex){
277                    logger.warning("Cannot close file " + filename);
278                    logger.warning(ex.toString());
279                }
280            }
281            /* return true on success */
282            return numEntries;
283        }
284    
285        /**Produces a single data entry in the exported file. Overwrite
286         * this method to produce formatted output of blockdata.
287         * @see #export(Object[] keys, Object[][] data)
288         */
289        protected abstract String getBlock(int blockIndex, Map blockdata);
290    
291        /**Produces the header section of the exported file. Overwrite
292         * this method to produce formatted output of the data returned by
293         * {@link #getHeaderData()}.
294         */
295        protected abstract String getHeader();
296    
297        /**Produces the footer section of the exported file. Overwrite
298         * this method to produce formatted output of the data returned by
299         * {@link #getFooterData()}.
300         */
301        protected abstract String getFooter(int NumEntries);
302    
303        /**Retrieve the file filter that determines which files can be selected
304         * as an export target. The default implementation accepts all files.
305         */
306        public FileFilter getFileFilter(){
307            return (new FileFilter(){
308                public boolean accept(File f){
309                    return (f.getName().endsWith(getExtension()) || f.isDirectory());
310                }
311    
312                public String getDescription(){
313                    return getName();
314                }
315            });
316        }
317    
318        /** Returns whether the client should try to read
319        * data that is not found in the table directly from the mp3 file.
320        * Defaults to true.
321        * @return whether to read id3 tags as a fallback
322        */
323        public boolean getFileFallback(){
324            return fileFallback;
325        }
326    
327        /** Sets whether the client should try to read
328        * data that is not found in the table directly from the mp3 file.
329        * Defaults to true.
330        * @param b whether to read id3 tags as a fallback
331        */
332        public void setFileFallback(boolean b){
333            fileFallback = b;
334        }
335    
336        /** Returns known instantiable sub-classes with a public no-argument
337        * constructor.
338        * @return the known instantiable sub-classes
339        */
340        public static String[] getImplementations(){
341            if(implementations == null){
342                implementations = new String[]{
343                    CSVExporter.class.getName(),
344                    M3uExporter.class.getName(),
345                    PLSExporter.class.getName(),
346                    WinampXMLPlaylistExporter.class.getName(),
347                    SansaPLAExporter.class.getName()
348                };
349            }
350            return implementations;
351        }
352    
353        /** Returns a string description of an exporter's target type.
354        * @return the name of the target type
355        */
356        public abstract String getName();
357    
358        /** Returns the file extension for an exporter's target file type.
359        * @return a file extension including the leading dot
360        */
361        public String getExtension(){
362            return "";
363        }
364    }