001    package net.sourceforge.mp3dings.utils;
002    
003    //TODO look for duplicate files using length() and getHash() methods.
004    //TODO: Set new Value using Pattern builder
005    //TODO: apply filters on individual cells
006    /* Mp3dings - manage mp3 meta-information
007     * Copyright (C) 2003 Moritz Ringler
008     * $Id: FileCopyRunnable.java,v 1.8 2006/09/04 12:32:27 ringler Exp $
009     *
010     * This program is free software; you can redistribute it and/or
011     * modify it under the terms of the GNU General Public License
012     * as published by the Free Software Foundation; either version 2
013     * of the License, or (at your option) any later version.
014     *
015     * This program is distributed in the hope that it will be useful,
016     * but WITHOUT ANY WARRANTY; without even the implied warranty of
017     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
018     * GNU General Public License for more details.
019     *
020     * You should have received a copy of the GNU General Public License
021     * along with this program; if not, write to the Free Software
022     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
023     */
024    
025    import java.awt.Frame;
026    import java.io.File;
027    import java.io.FileInputStream;
028    import java.io.FileOutputStream;
029    import java.io.IOException;
030    import java.lang.reflect.InvocationTargetException;
031    import java.nio.channels.FileChannel;
032    import java.nio.channels.FileLock;
033    import java.util.logging.Logger;
034    import javax.swing.JOptionPane;
035    import javax.swing.SwingUtilities;
036    import de.mospace.swing.StatusBar;
037    import net.sourceforge.mp3dings.Globals;
038    
039    /** This class copies files in a background thread. Progress
040    * is indicated in a Status Bar. In case of an exception
041    * file copying is suspended and the user is asked what to do in a JDialog.
042    * If the Status Bar is part of a container hierarchy
043    * the error dialog will be owned by the window ancestor of the Status bar.
044    **/
045    public class FileCopyRunnable implements Runnable{
046        private static final Logger logger = Logger.getLogger(FileCopyRunnable.class.getPackage().getName());
047        private int j = 0;
048        private File dest;
049        private StatusBar cpstatus;
050        private Integer errorAction;
051        private File[] src;
052    
053        /** Returns the StatusBar in which this FileCopyRunnable displays its
054        * status messages. **/
055        public StatusBar getStatusBar(){
056            return cpstatus;
057        }
058    
059        /** Returns the number of files copied so far. */
060        public int getFilesCopied(){
061            return j;
062        }
063    
064        public int getTotalFiles(){
065            return src.length;
066        }
067    
068        public FileCopyRunnable(File dest, File[] src){
069            try {
070                this.dest = dest.getCanonicalFile();
071            } catch (IOException ex){
072                logger.warning(ex.getMessage());
073            }
074    
075            cpstatus = new StatusBar(){
076                public void clear(){
077                }
078            };
079            cpstatus.setStatus(Globals.getMessage("COPY_WAIT",
080            new Object[]{
081                new Integer(src.length),
082                this.dest.getAbsolutePath()
083            })
084            );
085            this.src = src;
086        }
087    
088        /** Copies the file with abstract filename <code>in</code> to the
089        file with abstract filename <code>out</code>. Both files will be closed
090        before this method returns even if an error occurs.
091        @param in the file to read from
092        @param out the file to write to
093        @throws NullPointerException if one of the parameters is null
094        @throws FileNotFoundExecption if one of the files cannot be opened
095        @throws IOException if the destination file exists or cannot be locked
096        **/
097        private static void copyFile(File in, File out) throws IOException {
098            if(in == null || out == null){
099                throw new NullPointerException("null is not allowed here.");
100            }
101            try{
102                if(in.getCanonicalPath().equals(out.getCanonicalPath())){
103                    logger.info("Cannot copy file to itself: " + in);
104                    return;
105                }
106            } catch (IOException iox){
107                logger.warning("Error getting canonical path");
108                logger.warning(iox.toString());
109            }
110            File myOut = out;
111            FileChannel sourceChannel = null;
112            FileChannel destinationChannel = null;
113            FileLock targetLock = null;
114            try{
115                sourceChannel = new FileInputStream(in).getChannel();
116                if(myOut.isDirectory()){
117                    myOut = new File(myOut, in.getName());
118                }
119                if(myOut.exists()){
120                    throw new IOException("Destination file "+myOut.getName()+" exists.");
121                }
122                destinationChannel = new FileOutputStream(myOut).getChannel();
123                targetLock = destinationChannel.tryLock();
124                if (targetLock == null){
125                    throw new IOException("Cannot lock destination file.");
126                }
127                sourceChannel.transferTo(0, sourceChannel.size(),
128                destinationChannel);
129            } finally {
130                if (targetLock != null){
131                    targetLock.release();
132                }
133                if (sourceChannel != null && sourceChannel.isOpen()){
134                    sourceChannel.close();
135                }
136                if (destinationChannel != null && destinationChannel.isOpen()){
137                    destinationChannel.close();
138                }
139                //remove empty target files
140                if(myOut.length() == 0){
141                    myOut.delete();
142                }
143            }
144    
145        }
146    
147        public void run() {
148            /* this is necessary otherwise a new call to copyTo()
149            * will affect all unterminated copy actions */
150            boolean skipAll = false;
151    
152            final Integer maxFile = new Integer(src.length);
153            FILELOOP: for(int i = 0; i<src.length; i++){
154                final Integer currFile = new Integer(i+1);
155                cpstatus.setStatus(Globals.getMessage("COPY_PROGRESS",
156                        new Object[]{ dest.toString(), currFile, maxFile, src[i].getName() }));
157                try{
158                    copyFile(src[i],dest);
159                    j++;
160                } catch (Exception ex) {
161                    if(skipAll){
162                        continue;
163                    }
164                    final String msg = ex.getLocalizedMessage();
165                    Throwable invokeAndWaitError = null;
166                    try{
167                    SwingUtilities.invokeAndWait(
168                    new Runnable(){
169                        public void run(){
170                            Object[] options =
171                            Globals.getStringArray("COPY_WARNING_OPTIONS");
172                            String warning = Globals.getMessage("COPY_WARNING_MESSAGE",
173                                        new Object[]{
174                                            currFile,
175                                            new Integer(src.length),
176                                            dest.getAbsolutePath(),
177                                            msg
178                                        }
179                                    );
180                            cpstatus.setStatus(warning);
181                            errorAction = new Integer(
182                                JOptionPane.showOptionDialog(
183                                    SwingUtilities.getAncestorOfClass(Frame.class,
184                                    cpstatus),
185                                    warning,
186                                    Globals.getString("WARNING"),
187                                    JOptionPane.DEFAULT_OPTION,
188                                    JOptionPane.WARNING_MESSAGE,
189                                    null, options, null
190                                )
191                            );
192                        }
193                    }
194                    );
195                    } catch (InvocationTargetException ex2){
196                        invokeAndWaitError = ex2;
197                    } catch (InterruptedException ex2){
198                        invokeAndWaitError = ex2;
199                    }
200                    if(invokeAndWaitError != null){
201                        logger.severe(invokeAndWaitError.toString());
202                        errorAction = new Integer(-1);
203                    }
204                    switch (errorAction.intValue()){
205                        case 0:
206                        i--;
207                        continue;
208                        case 1:
209                        continue;
210                        case 2:
211                        skipAll = true; continue;
212                        default:
213                        break FILELOOP;
214                    }
215                }
216            }
217            SwingUtilities.invokeLater(
218                new Runnable(){
219                    public void run(){
220                        finished();
221                    }
222                }
223            );
224        }
225    
226        /** Should be overwritten. */
227        public void finished(){
228        }
229    };
230