001    package net.sourceforge.mp3dings.filter;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2003 Moritz Ringler
005     * $Id: BeanShellFilter.java 67 2007-10-23 08:45:08Z 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.util.prefs.Preferences;
023    import java.io.IOException;
024    import bsh.EvalError;
025    import bsh.Interpreter;
026    import de.mospace.lang.FullTextString;
027    
028    /** A filter that is based on a bean-shell script.
029     * @author Moritz Ringler
030     * @version $Revision: 67 $ ($Date: 2007-10-23 10:45:08 +0200 (Di, 23 Okt 2007) $)
031     */
032    public class BeanShellFilter extends FilterBean{
033        static final long serialVersionUID = 1303465009936550114L;
034    
035        private transient Filter bshFilter;
036        private static transient Interpreter bsh;
037        private final static String DEFAULT_METHODBODY =
038            "if(a instanceof String){\n"+
039            "    result = a.concat(\"\");\n"+
040            "} else if (a instanceof Boolean){\n"+
041            "    result = ! (!a);\n"+
042            "} else if (a instanceof Number){\n"+
043            "    result = a * 1;\n"+
044            "} else {\n"+
045            "    result = a;\n" +
046            "}";
047        private String methodBody = DEFAULT_METHODBODY;
048        private transient Exception compileException;
049    
050        private Object[] testObjects = new Object[]{
051            "test",
052            (Number) new Double(0.0),
053            Boolean.TRUE
054        };
055    
056        public BeanShellFilter(){
057            this(DEFAULT_METHODBODY);
058        }
059    
060        public BeanShellFilter(String filterMethodBody){
061            if (bsh == null){
062                bsh = new Interpreter();
063                bsh.setClassLoader(getClass().getClassLoader());
064            }
065            setMethodBodyImpl(filterMethodBody);
066        }
067    
068        private void changeMethodBody(String newMethodBody) throws EvalError, ClassCastException{
069            methodBody = newMethodBody;
070            compile();
071        }
072    
073        private void compile() throws EvalError, ClassCastException{
074            bshFilter = (Filter) bsh.eval(
075            "new net.sourceforge.mp3dings.filter.Filter(){" +
076                "public Object filter(Object a){\n" +
077                    "Object result;\n" +
078                    methodBody +
079                    "return result;\n" +
080                "}\n" +
081            "};\n");
082            Object val, result;
083            for(int i=0; i<testObjects.length; i++){
084                val = testObjects[i];
085                result = bshFilter.filter(val);
086                if(!(
087                    result == null ||
088                    val.getClass().isInstance(result) ||
089                    ((val instanceof Number) && (result instanceof Number))
090                )){
091                    throw new ClassCastException("Result for input type " +
092                        val.getClass().getName() + " is of type " + result.getClass().getName() + ".");
093                }
094            }
095        }
096    
097        private synchronized void setMethodBodyImpl(String filterMethodBody){
098            String oldMethod = methodBody;
099            boolean oldSavable = isSavable();
100            Exception oldException = compileException;
101            try{
102                changeMethodBody(filterMethodBody);
103                compileException = null;
104            } catch (Exception ex){
105                compileException = ex;
106            }
107            boolean savable = isSavable();
108            if(compileException != oldException){
109                firePropertyChange("compileError", oldException, compileException);
110            }
111            if( oldSavable != savable){
112                firePropertyChange("savable", oldSavable, savable);
113            }
114            if(! oldMethod.equals(methodBody)){
115                firePropertyChange("methodBody", oldMethod, methodBody);
116            }
117        }
118    
119        public void setMethodBody(String filterMethodBody){
120            setMethodBodyImpl(filterMethodBody);
121        }
122    
123        public Exception getCompileError(){
124            return compileException;
125        }
126    
127        public boolean isSavable(){
128            return (compileException == null);
129        }
130    
131        public void save(Preferences pref, String key){
132            super.save(pref, key);
133        }
134    
135        public String getMethodBody(){
136            return methodBody;
137        }
138    
139        public boolean equals(Object o){
140            if(this == o){
141                return true;
142            }
143            boolean result = false;
144            if(o instanceof BeanShellFilter){
145                BeanShellFilter other = (BeanShellFilter) o;
146                result = result && ((methodBody == null)
147                        ? (other.methodBody == null)
148                        : methodBody.equals(other.methodBody));
149                result = result && ((getName() == null)
150                        ? (other.getName() == null)
151                        : getName().equals(other.getName()));
152            }
153            return result;
154        }
155    
156        public int hashCode(){
157            int result = 19;
158            result = 43 * result +
159                    ((methodBody == null)? 0 : methodBody.hashCode());
160            result = 43 * result +
161                    ((getName() == null)? 0 : getName().hashCode());
162            return result;
163        }
164    
165    
166        /** Filters the Object val.
167        * @param val the object to filter
168        * @return the filtered object. It must be an instance of the class of val.
169        *         Implementations should assure this with an assert statement
170        *         such as<p>
171        *         <code>assert returnval == null || val == null || val.getClass().isInstance(returnval);</code>
172        **/
173        public Object filter(Object val){
174            Object result = val;
175            if(val != null && bshFilter != null){
176                boolean isFullTextString = val instanceof FullTextString;
177                /* turn into String */
178                if(isFullTextString){
179                  result = val.toString();
180                }
181                /* do filtering */
182                result = bshFilter.filter(result);
183                /* turn back into FullTextString if necessary */
184                if(isFullTextString && result != null){
185                    result = new FullTextString(result.toString());
186                }
187            }
188            return result;
189        }
190    
191        private void readObject(java.io.ObjectInputStream in)
192            throws IOException, ClassNotFoundException{
193                in.defaultReadObject();
194                if (bsh == null){
195                    bsh = new Interpreter();
196                    bsh.setClassLoader(ClassLoader.getSystemClassLoader());
197                }
198                setMethodBody(DEFAULT_METHODBODY);
199                setMethodBody(methodBody);
200        }
201    
202    }