001    // GraphLab Project: http://graphlab.sharif.edu
002    // Copyright (C) 2008 Mathematical Science Department of Sharif University of Technology
003    // Distributed under the terms of the GNU General Public License (GPL): http://www.gnu.org/licenses/
004    package graphlab.platform;
005    
006    import graphlab.platform.Application;
007    import graphlab.platform.lang.ArrayX;
008    import graphlab.platform.lang.FromStringProvider;
009    import graphlab.platform.core.BlackBoard;
010    import graphlab.platform.core.exception.ExceptionOccuredData;
011    import graphlab.platform.extension.ExtensionLoader;
012    import graphlab.platform.preferences.lastsettings.StorableOnExit;
013    
014    import java.awt.*;
015    import java.io.*;
016    import java.math.BigDecimal;
017    import java.math.BigInteger;
018    import java.util.HashMap;
019    import java.util.Scanner;
020    import java.util.jar.JarEntry;
021    import java.util.jar.JarOutputStream;
022    
023    /**
024     * some usefill and handy static utilities.
025     *
026     * @author Azin Azadi
027     * @author Reza Mohammadi mohammadi
028     */
029    public class StaticUtils {
030    
031        /**
032         * The linear Operation AX+B
033         *
034         * @param a
035         * @param b
036         * @param x
037         * @return
038         * @throws Exception
039         */
040        public Double[] linearOperation(Double[] a, Double[] b, Double[] x)
041                throws Exception {
042            if ((a.length != b.length) || (a.length != x.length)) {
043                throw new Exception("Problem in dimensions!");
044            }
045            int n = a.length;
046            Double[] result = new Double[n];
047            for (int i = 0; i < n; i++)
048                result[i] = (double) (a[i] * x[i] + b[i]);
049            return result;
050        }
051    
052        public static void putInJar(File directory, JarOutputStream jos, String prefix) throws IOException, FileNotFoundException, Exception {
053            FileInputStream fis;
054            File[] files = directory.listFiles();
055    
056            for (int n = 0; n < files.length; n++) {
057    
058                if (files[n].isDirectory()) {
059                    putInJar(files[n], jos, prefix + files[n].getName() + "/");
060                } else {
061                    jos.putNextEntry(new JarEntry(prefix + files[n].getName()));
062                    fis = new FileInputStream(files[n]);
063    
064                    copyStream(fis, jos);
065    
066                    fis.close();
067                    jos.closeEntry();
068                }
069            }
070        }
071    
072        public static void copyFile(File in, File out) throws Exception {
073            FileInputStream fis = new FileInputStream(in);
074            FileOutputStream fos = new FileOutputStream(out);
075            byte[] buf = new byte[1024];
076            int i = 0;
077            while ((i = fis.read(buf)) != -1) {
078                fos.write(buf, 0, i);
079            }
080            fis.close();
081            fos.close();
082        }
083    
084        public static void copyStream(InputStream is, OutputStream out) throws Exception {
085            byte[] buf = new byte[1024];
086            int i = 0;
087            while ((i = is.read(buf)) != -1) {
088                out.write(buf, 0, i);
089            }
090        }
091    
092        /**
093         * @param classname
094         * @param data
095         * @return the actual object which is a 'classname' object and have toString: 'data'
096         */
097        public static Object fromString(String classname, String data) {
098            Object o = data;
099            if ("null".equalsIgnoreCase(data)
100                    && !(String.class.getName().equals(classname)))
101                return null;
102    
103            if (String.class.getName().equals(classname)) return data;
104    
105            if (Integer.class.getName().equals(classname)) return new Integer(data);
106    
107            if (BigInteger.class.getName().equals(classname)) return new BigInteger(data);
108    
109            if (Double.class.getName().equals(classname)) return new Double(data);
110    
111            if (Character.class.getName().equals(classname)) return new Character(data.charAt(0));
112    
113            if (Color.class.getName().equals(classname)) return color(data);
114    
115            if (BigDecimal.class.getName().equals(classname)) return new BigDecimal(data);
116    
117            if (Boolean.class.getName().equals(classname)) return new Boolean(data);
118    
119            if (classname.equals(Font.class.getName())) return str2Font(data);
120    
121            if (classname.equals(ArrayX.class.getName())) return ArrayX.fromString(data);
122    
123            FromStringProvider fromStringProvider = pr.get(classname);
124            if (fromStringProvider == null)
125                return null;
126            else
127                return fromStringProvider.fromString(data);
128        }
129    
130        static HashMap<String, FromStringProvider> pr = new HashMap<String, FromStringProvider>();
131    
132        /**
133         * Adds a new FromStringProvider to current ones.
134         *
135         * @param className
136         * @param pro
137         */
138        public static void setFromStringProvider(String className, FromStringProvider pro) {
139            pr.put(className, pro);
140        }
141    
142        private static Color color(String data) {
143            Color o;
144            data = data.replace('[', ' ');
145            data = data.replace(']', ' ');
146            data = data.replace('.', ' ');
147            data = data.replace('.', ' ');
148            data = data.replace('.', ' ');
149            data = data.replace('=', ' ');
150            data = data.replace('=', ' ');
151            data = data.replace('=', ' ');
152            data = data.replace(',', ' ');
153            data = data.replace(',', ' ');
154            data = data.replace(',', ' ');
155            Scanner sc = new Scanner(data);
156            sc.next("java");
157            sc.next("awt");
158            sc.next("Color");
159            sc.next("r");
160            int r = sc.nextInt();
161            sc.next();
162            int g = sc.nextInt();
163            sc.next();
164            int b = sc.nextInt();
165            sc.close();
166            o = new Color(r, g, b);
167            return o;
168        }
169    
170        /**
171         * converts a String that generated with standard toString() of a font object to a Font Object
172         * a sample input is: "java.awt.Font[family=Dialog,name=tahoma,style=plain,size=12]"
173         */
174        public static Font str2Font(String fontToStringed) {
175            String data = fontToStringed;
176            data = data.replace('[', ' ');
177            data = data.replace(']', ' ');
178            data = data.replace('.', ' ');
179            data = data.replace('.', ' ');
180            data = data.replace('.', ' ');
181            data = data.replace('=', ' ');
182            data = data.replace('=', ' ');
183            data = data.replace('=', ' ');
184            data = data.replace(',', ' ');
185            data = data.replace(',', ' ');
186            data = data.replace(',', ' ');
187            Scanner sc = new Scanner(data);
188            sc.next("java");
189            sc.next("awt");
190            sc.next("Font");
191            sc.next("family");
192            String family = sc.next();
193            sc.next("name");
194            String name = sc.next();
195            sc.next("style");
196            String _style = sc.next();
197            sc.next("size");
198            int size = sc.nextInt();
199            int style;
200    
201    //        this is the original part of to string that creates the style string
202    //        if (isBold()) {
203    //            strStyle = isItalic() ? "bolditalic" : "bold";
204    //        } else {
205    //            strStyle = isItalic() ? "italic" : "plain";
206    //        }
207    
208            if (_style.equals("bolditalic"))
209                style = Font.BOLD | Font.ITALIC;
210            else if (_style.equals("italic"))
211                style = Font.ITALIC;
212            else if (_style.equals("bold"))
213                style = Font.BOLD;
214            else
215                style = Font.PLAIN;
216            Font f = new Font(name, style, size);
217            return f;
218        }
219    
220    
221        /**
222         * loads(includes its automatically generated menues, ...) a single extension into application
223         *
224         * @param s
225         * @param blackboard
226         */
227        public static void loadSingleExtension(Class s) {
228            Object extension = ExtensionLoader.loadExtension(s);
229            if (extension != null) {
230                StorableOnExit.SETTINGS.registerSetting(extension, "Extention Options");
231                ExtensionLoader.handleExtension(Application.blackboard, extension);
232            }
233        }
234    
235        /**
236         * return the Application Instance which created b during initialization
237         *
238         * @param blackboard
239         * @return
240         */
241        public static Application getApplicationInstance(BlackBoard blackboard) {
242            return blackboard.getData(Application.APPLICATION_INSTANCE);
243        }
244    
245        public static void addExceptiontoLog(Throwable e, BlackBoard b) {
246            ExceptionOccuredData ee = new ExceptionOccuredData(e);
247            b.setData(ExceptionOccuredData.EVENT_KEY, ee);
248        }
249    
250        public static boolean isImplementing(Class cl, Class inter) {
251            if (cl.equals(inter))
252                return true;
253            Class[] interfaces = cl.getInterfaces();
254            for (Class anInterface : interfaces)
255                if (isImplementing(anInterface, inter))
256                    return true;
257    
258            return false;
259        }
260    }