001    package net.sourceforge.mp3dings.utils;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2003 Moritz Ringler
005     * $Id: ChecksumFactory.java,v 1.6 2007/03/29 16:03:02 ringler Exp $
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.beans.BeanInfo;
023    import java.beans.IntrospectionException;
024    import java.beans.Introspector;
025    import java.beans.PropertyDescriptor;
026    import java.io.File;
027    import java.io.FileInputStream;
028    import java.io.IOException;
029    import java.io.InputStream;
030    import java.lang.reflect.Method;
031    import java.util.Iterator;
032    import java.util.Map;
033    import java.util.TreeMap;
034    import java.util.logging.Logger;
035    import de.mospace.lang.ClassLoaderProvider;
036    import de.mospace.lang.MinimalClassLoaderProvider;
037    import helliker.id3.ID3v1Tag;
038    import helliker.id3.MP3File;
039    
040    
041    /** A base class for beans.
042     * @author Moritz Ringler
043     * @version $Revision: 1.6 $ ($Date: 2007/03/29 16:03:02 $)
044     */
045    public class ChecksumFactory extends Bean{
046        private static final Logger logger = Logger.getLogger(ChecksumFactory.class.getPackage().getName());
047        static final long serialVersionUID = -6845365531496638057L;
048    
049        private String algorithm = null;
050        private String encoding = null;
051        private transient Object jacksumAPI;
052        private transient Map algorithmMap;
053        private transient Map encodingMap;
054        private transient String jsVersion = null;
055        private boolean ignoreTags = false;
056        private ClassLoaderProvider clp = new MinimalClassLoaderProvider();
057        public final static int BUFFERSIZE = 1 << 12;
058        private transient ClassLoader jacksumCL = clp.getClassLoader();
059        private long maxEnd = 0l;
060        private long maxStart = 0l;
061    
062        public ChecksumFactory(){
063        }
064    
065        public ChecksumFactory(ClassLoaderProvider clp){
066            this.clp = clp;
067        }
068    
069        private void initJacksum(){
070            jacksumCL = clp.getClassLoader();
071            /* if jacksum is present on the classpath or in ${user.home}/.mp3dings/lib
072             * use reflection to acces the JackSum API.
073             * This does not require JackSum to be present at either compile time
074             * or run time. */
075            try{
076                Class jsClass = Class.forName("jonelo.jacksum.JacksumAPI", true, jacksumCL);
077                jacksumAPI = jsClass.newInstance();
078    
079                /* retrieve available algorithms, put GUI names into algorithms
080                 * construct mapping GUI-name -> name
081                 */
082                Method jsMethod = jsClass.getMethod("getAvailableAlgorithms", null);
083                algorithmMap = (Map) jsMethod.invoke(jacksumAPI, null);
084                if(algorithm == null && algorithmMap.keySet().contains("sha1")){
085                    algorithm = (String) algorithmMap.get("sha1");
086                }
087                Map inverseMap = new TreeMap();
088                Iterator it = algorithmMap.keySet().iterator();
089                while(it.hasNext()){
090                    Object key = it.next();
091                    /* invert map and
092                     * wrap key into array for Method.invoke(..., Object[])
093                     */
094                    inverseMap.put(algorithmMap.get(key), new Object[]{key});
095                }
096                if(algorithm == null){
097                    String[] algorithms = getAlgorithms();
098                    if(algorithms.length > 0){
099                        algorithm = algorithms[0];
100                    }
101                }
102    
103                algorithmMap = inverseMap;
104    
105               /* retrieve available encodings, put GUI names into encodings
106               * construct mapping GUI-name -> name
107               */
108               jsMethod = jsClass.getMethod("getAvailableEncodings", null);
109               encodingMap = (Map) jsMethod.invoke(jacksumAPI, null);
110               if(encoding == null && encodingMap.keySet().contains("base64")){
111                   encoding = (String) encodingMap.get("base64");
112               }
113               inverseMap = new TreeMap();
114               it = encodingMap.keySet().iterator();
115               while(it.hasNext()){
116                   Object key = it.next();
117                    /* invert map and
118                     * wrap key into array for Method.invoke(..., Object[])
119                     */
120                   inverseMap.put(encodingMap.get(key),new Object[]{key});
121               }
122               encodingMap = inverseMap;
123               if(encoding == null){
124                   String[] encodings = getAlgorithms();
125                   if(encodings.length > 0){
126                       encoding = encodings[0];
127                   }
128               }
129    
130                /* get Jacksum version */
131                jsMethod = jsClass.getMethod("getVersionString", null);
132                jsVersion = (String) jsMethod.invoke(jacksumAPI, null);
133            } catch (ClassNotFoundException ex){
134                jsVersion = "JACKSUM_NOT_FOUND";
135            } catch (Exception ex){
136                jsVersion = "JACKSUM_NOT_FOUND";
137                logger.warning("Error loading jacksum.");
138                logger.warning(ex.toString());
139            }
140        }
141    
142        private void readObject(java.io.ObjectInputStream in)
143            throws IOException, ClassNotFoundException{
144                in.defaultReadObject();
145                if (clp == null){
146                    clp = new MinimalClassLoaderProvider();
147                }
148        }
149    
150        public Checksum getChecksum(){
151            Object result = null;
152            if(isJacksumAvailable()){
153                Class jsClass = jacksumAPI.getClass();
154                Class[] argcl = new Class[]{String.class};
155                try{
156                    Method jsMethod = jsClass.getMethod("getChecksumInstance", argcl);
157                    result = jsMethod.invoke(jacksumAPI,
158                        (Object[]) algorithmMap.get(algorithm));
159                    jsClass = result.getClass(); //AbstractChecksum subclass
160                    jsMethod = jsClass.getMethod("setEncoding", argcl);
161                    jsMethod.invoke(result, (Object[]) encodingMap.get(encoding));
162                } catch (Exception ex){
163                    throw new Error(ex);
164                }
165            }
166            if(result != null){
167                try{
168                    result = new AbstractChecksumWrapper(result,
169                        jacksumCL);
170                } catch (RuntimeException ex){
171                    throw ex;
172                } catch (Exception ignore){
173                }
174            }
175            return (Checksum) result;
176        }
177    
178        public boolean isJacksumAvailable(){
179            if(jsVersion == null || !clp.getClassLoader().equals(jacksumCL)){
180                initJacksum();
181            }
182            return (jacksumAPI != null);
183        }
184    
185        public void setAlgorithm(String algorithm){
186            String oldValue = this.algorithm;
187            this.algorithm = algorithm;
188            firePropertyChange("algorithm", oldValue, algorithm);
189        }
190    
191        public String getAlgorithm(){
192            return algorithm;
193        }
194    
195        public String[] getAlgorithms(){
196            isJacksumAvailable(); //called for the side effect
197            return (String[]) algorithmMap.keySet().toArray(new String[0]);
198        }
199    
200        public boolean getIgnoreTags(){
201            return ignoreTags;
202        }
203    
204        public void setIgnoreTags(boolean b){
205            if(ignoreTags != b){
206                ignoreTags = b;
207                firePropertyChange("ignoreTags", !b, b);
208            }
209        }
210    
211        public void setMaxBytesFromStart(long fromStart){
212            if(fromStart < 0){
213                throw new IllegalArgumentException();
214            }
215            if(maxStart != fromStart){
216                long oldStart = maxStart;
217                maxStart = fromStart;
218                firePropertyChange("maxBytesFromStart", new Long(oldStart), new Long(maxStart));
219            }
220        }
221    
222        public void setMaxBytesFromEnd(long fromEnd){
223            if(fromEnd < 0){
224                throw new IllegalArgumentException();
225            }
226            if(maxEnd != fromEnd){
227                long oldEnd = maxEnd;
228                maxEnd = fromEnd;
229                firePropertyChange("maxBytesFromEnd", new Long(oldEnd), new Long(maxEnd));
230            }
231        }
232    
233        public long getMaxBytesFromStart(){
234            return maxStart;
235        }
236    
237        public long getMaxBytesFromEnd(){
238            return maxEnd;
239        }
240    
241        public void setEncoding(String encoding){
242            String oldValue = this.encoding;
243            this.encoding = encoding;
244            firePropertyChange("encoding", oldValue, encoding);
245        }
246    
247        public String getEncoding(){
248            return encoding;
249        }
250    
251        public String[] getEncodings(){
252            isJacksumAvailable(); //called for the side effect
253            return(String[]) encodingMap.keySet().toArray(new String[0]);
254        }
255    
256        public void setClassLoaderProvider(ClassLoaderProvider clp){
257            this.clp = clp;
258        }
259    
260        static {
261            try {
262                // Mark some properties transient
263                BeanInfo info = Introspector.getBeanInfo(ChecksumFactory.class);
264                PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors();
265                for (int i = 0; i < propertyDescriptors.length; ++i) {
266                    PropertyDescriptor pd = propertyDescriptors[i];
267                    if (pd.getName().equals("jacksumAvailable") ||
268                        pd.getName().equals("algorithms") ||
269                        pd.getName().equals("encodings")
270                    ) {
271                        pd.setValue("transient", Boolean.TRUE);
272                    }
273                }
274            } catch (IntrospectionException e) {
275            }
276        }
277    
278        private class AbstractChecksumWrapper implements Checksum{
279            private final Object abstractChecksum;
280            private final boolean myIgnoreTags = ignoreTags;
281            private final long myMaxStart = maxStart;
282            private final long myMaxEnd = maxEnd;
283            private final Method updateBOL, updateB;
284            private final Method readFile;
285            private final Class acClass;
286            private final static int ID3V1_TAG_SIZE = 128;
287            private final Integer ZERO = new Integer(0);
288            private final Integer OFFSET = new Integer(BUFFERSIZE);
289    
290            public AbstractChecksumWrapper(Object ac, ClassLoader cl) throws Exception{
291                abstractChecksum = ac;
292                acClass = Class.forName("jonelo.jacksum.algorithm.AbstractChecksum", true, cl);
293                updateBOL = acClass.getMethod("update", new Class[]{
294                    (new byte[0]).getClass(),
295                    int.class,
296                    int.class
297                });
298                updateB = acClass.getMethod("update", new Class[]{int.class});
299                readFile = acClass.getMethod("readFile", new Class[]{String.class});
300            }
301    
302            public byte[] getByteArray(){
303                return (byte[]) delegate("getByteArray");
304            }
305    
306            public String getFormattedValue(){
307                return (String) delegate("getFormattedValue");
308            }
309    
310            /** @return number of bytes read **/
311            public long readFile(File f){
312                return readFile(f, null);
313            }
314    
315            /** @return number of bytes read **/
316            public long readFile(File f, byte[] buffer){
317                long result = readFileImpl(f,
318                    (buffer != null && buffer.length == BUFFERSIZE)?
319                    buffer : null);
320                return result;
321            }
322    
323            private long readFileImpl(File f, byte[] buffer){
324                long start = 0;
325                long maxlength = f.length();
326                long bytesread = 0;
327                try{
328                    if(ignoreTags){
329                        /* look for the beginning of the audio data */
330                        start = (new MP3File(f)).getAudioOffset();
331                        maxlength -= start;
332                        if((new ID3v1Tag(f)).tagExists()){
333                            maxlength -= ID3V1_TAG_SIZE;
334                        }
335                    }
336                    bytesread = (updateBOL == null)? 0l : readFileImpl(f, start, maxlength, buffer);
337                } catch (Exception ex){
338                    logger.warning("Error calculating checksum.");
339                    logger.warning(ex.toString());
340                    reset();
341                }
342                return bytesread;
343            }
344    
345            private long readFileImpl(File f, long start, long maxlength, byte[] buffer) throws Exception{
346                boolean blockLimits = myMaxStart != 0l || myMaxEnd != 0l;
347                /* read block from start of file */
348                long blocklength = (blockLimits)? Math.min(maxlength, myMaxStart) : maxlength;
349                long blockstart = start;
350                long bytesread = readBlock(f, blockstart, blocklength, buffer);
351                /* read block from end of file */
352                if(blockLimits){
353                    blocklength = Math.min(maxlength-blocklength, myMaxEnd);
354                    if(blocklength > 0l){
355                        blockstart = maxlength - blocklength;
356                        bytesread += readBlock(f, blockstart, blocklength, buffer);
357                    }
358                }
359                return bytesread;
360            }
361    
362            private long readBlock(File f, long start, long maxlength, byte[] buffer) throws Exception{
363                long bytesread = 0l;
364                InputStream bis = null;
365                bis = new FileInputStream(f);
366                try {
367                    //bis = new FileInputStream(f);
368                    bis.skip(start);
369                    reset();
370                    int len = 0;
371                    if(buffer == null) {
372                        buffer = new byte[BUFFERSIZE];
373                    }
374                    while ( (len = bis.read(buffer)) > -1) {
375                        if(bytesread + len <= maxlength ){
376                            uncheckedUpdate(buffer, len);
377                            bytesread += len;
378                        } else {
379                            len = (int) (maxlength - bytesread);
380                            uncheckedUpdate(buffer, len);
381                            bytesread += len;
382                            break;
383                        }
384                    }
385                } finally {
386                    bis.close();
387                }
388                return bytesread;
389            }
390    
391            public long getValue(){
392                Long result = (Long) delegate("getValue");
393                return (result == null) ? 0l : result.longValue();
394            }
395    
396            public void reset(){
397                delegate("reset");
398            }
399    
400            private void uncheckedUpdate(byte[] b, int len) throws Exception{
401                updateBOL.invoke(abstractChecksum,
402                        new Object[]{b, ZERO, (len == BUFFERSIZE)? OFFSET : new Integer(len)});
403            }
404    
405            public void uncheckedUpdate(Object[] b) throws Exception{
406                updateB.invoke(abstractChecksum, b);
407            }
408    
409            public void update(byte[] b, int off, int len){
410                if(updateBOL != null){
411                    try{
412                        updateBOL.invoke(abstractChecksum,
413                        new Object[]{b, new Integer(off), new Integer(len)});
414                    } catch (Exception ex){
415                        throw new Error(ex);
416                    }
417                }
418            }
419    
420            public void update(int b){
421                if(updateB != null){
422                    try{
423                        updateB.invoke(abstractChecksum,
424                        new Object[]{new Integer(b)});
425                    } catch (Exception ex){
426                        throw new Error(ex);
427                    }
428                }
429            }
430    
431            private Object delegate(String method, Class[] argTypes, Object[] args){
432                Object result = null;
433                try{
434                    Method m = acClass.getMethod(method, argTypes);
435                    result = m.invoke(abstractChecksum, args);
436                } catch (Exception ex){
437                    throw new Error(ex);
438                }
439                return result;
440            }
441    
442            private Object delegate(String method){
443                return delegate(method, null, null);
444            }
445    
446        }
447    }