ToolBox.java
001 /*
002  * This class is part of DocWhatsUp, a bug profiling and -reporting lib.
003  
004  * Copyright (C)
005  
006  * This library is free software; you can redistribute it and/or modify it
007  * under the terms of the GNU General Public License as published by the
008  * Free Software Foundation; either version 2 of the License, or (at your
009  * option) any later version.
010  
011  * This program is distributed in the hope that it will be useful, but
012  * WITHOUT ANY WARRANTY; without even the implied warranty of
013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
014  * Public License for more details.
015  *  
016  * You should have received a copy of the GNU General Public License along
017  * with this program; if not, write to the Free Software Foundation, Inc.,
018  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
019  
020  * EXTENSION:
021  * Linking DocWhatsUp statically or dynamically with other modules is making a
022  * combined work based on DocWhatsUp.  Thus, the terms and conditions of the 
023  * GNU General Public License cover the whole combination.
024  *
025  * As a special exception, the copyright holder of DocWhatsUp give you
026  * permission to link DocWhatsUp with independent modules that communicate with
027  * DocWhatsUp solely through the DocWhatsUp.java interface, regardless of the 
028  * license terms of these independent modules, and to copy and distribute the
029  * resulting combined work under terms of your choice, provided that
030  * every copy of the combined work is accompanied by a complete copy of
031  * the source code of DocWhatsUp (the version of DocWhatsUp used to produce the
032  * combined work), being distributed under the terms of the GNU General
033  * Public License plus this exception.  An independent module is a module
034  * which is not derived from or based on DocWhatsUp.
035 
036  * Note that people who make modified versions of DocWhatsUp are not obligated
037  * to grant this special exception for their modified versions; it is
038  * their choice whether to do so.  The GNU General Public License gives
039  * permission to release a modified version without this exception; this
040  * exception also makes it possible to release a modified version which
041  * carries forward this exception.
042  
043  * Author: Philipp Bartsch; codeshaker@gmx.net
044  */
045 
046 package org.shaker.dwu;
047 
048 import java.awt.Toolkit;
049 import java.awt.Window;
050 import java.io.BufferedReader;
051 import java.io.File;
052 import java.io.FileInputStream;
053 import java.io.FileOutputStream;
054 import java.io.FileWriter;
055 import java.io.IOException;
056 import java.io.InputStream;
057 import java.io.InputStreamReader;
058 import java.io.OutputStreamWriter;
059 import java.io.PrintWriter;
060 import java.util.Arrays;
061 import java.util.Collections;
062 import java.util.List;
063 import java.util.Locale;
064 import java.util.ResourceBundle;
065 
066 /**
067  * This class contains different useful static methods.
068  
069  @author <A HREF="mailto:codeshaker@gmx.net">
070  *            Philipp Bartsch (codeshaker@gmx.net)</A>
071  *            <A HREF="../../../../gpl.txt">GPL License</A>
072  */
073 final class ToolBox {
074 
075     /**OS depended path separator*/
076     private static final String FILE_SEP = System.getProperty("file.separator");
077     /**DWU`s output folder, located in ~/.docwhatsup*/
078             static final String DWU_PATH = System.getProperty("user.home")
079                                                               + FILE_SEP
080                                                               ".docwhatsup"
081                                                               + FILE_SEP;
082     /**File representation of DWU`s path.*/
083             static final File      DWU_DIR  = new File(DWU_PATH);
084 
085             static final File    LOG_FILE = new File(DWU_PATH + "error.log");        
086 
087     /**Localization ressources*/
088     private static          ResourceBundle lang
089                          = ResourceBundle.getBundle("l10n",
090                                                      Locale.getDefault());
091     
092     /**
093      * Invisible constructor. This class is not meant to be instantiated.
094      */
095     private ToolBox () {}
096     
097     /**
098      * This method create the settings folder and ships generic, default 
099      * settings at the very first startup.
100      */
101     static void checkUp () {        
102         if (!DWU_DIR.exists()) {
103             try {            
104                 DWU_DIR.mkdir();
105                 final StringBuffer settings = new StringBuffer();
106                 String line;
107                 // read configuration
108                 final InputStream inStream = ClassLoader
109                                              .getSystemClassLoader()
110                                              .getResourceAsStream("settings.dwu");            
111                 final InputStreamReader stReader = new InputStreamReader(inStream);
112                 final BufferedReader bufReader = new BufferedReader(stReader);
113                 while ((line = bufReader.readLine()) != null) {
114                     settings.append(line + BugMail.NEW_LINE);
115                 }
116                 inStream.close();
117                 stReader.close();
118                 bufReader.close();
119                 // write configuration                
120                 final File settingsFile = Settings.getSettingsFile()
121                 settingsFile.createNewFile();
122                 final FileWriter writer = new FileWriter(settingsFile);
123                 writer.write(settings.toString());
124                 writer.close();    
125             catch (Exception e) {                
126                 logException(e);                
127             }
128         }
129     }
130     
131     /**
132      * Logs a string in a DWU`s LogFile ($DWU_PATH/error.log). This method is 
133      * used to log internal errors.
134      @see ToolBox#DWU_PATH if you want to know, where DWU_PATH is located
135      
136      @param exception    the exception object
137      */
138     static void logException (final Exception exception) {
139         try {
140             Toolkit.getDefaultToolkit().beep();
141             exception.printStackTrace(DocWhatsUp.PRINTWRITER);            
142             if (!LOG_FILE.exists())
143                 LOG_FILE.createNewFile();
144             FileOutputStream fos = new FileOutputStream(LOG_FILE);
145             OutputStreamWriter writer = new OutputStreamWriter(fos, 
146                                                                "ISO-8859-1");            
147             PrintWriter printWriter = new PrintWriter(writer, 
148                                                       true);
149             printWriter.println(DocWhatsUp.STACKWR.toString());
150             fos.close();                        
151             writer.close();
152             printWriter.close();            
153         catch (Exception e) {
154             System.out.println("Unknown error: " + e.getMessage());
155         }
156     }
157     
158     /**
159      * Returns true, if there`s an existing log file in the dwu folder.
160      
161      @return logfile existence flag
162      */
163     static boolean existsLogFile () {
164         return LOG_FILE.exists();
165     }
166     
167     /**
168      * Returns the content of the logfile or an empty string, if not existing.
169      
170      @return logged text or an empty string, if missing
171      */
172     static String getLogText () {
173         final StringBuffer logtext = new StringBuffer();
174         try {
175             String line;    
176             // read content
177             InputStream inStream = new FileInputStream(LOG_FILE);            
178             InputStreamReader stReader = new InputStreamReader(inStream);
179             BufferedReader bufReader = new BufferedReader(stReader);
180             while ((line = bufReader.readLine()) != null) {
181                 logtext.append(line + BugMail.NEW_LINE);
182             }
183             inStream.close();
184             stReader.close();
185             bufReader.close();
186             return logtext.toString();
187         catch (IOException ioe) {
188             return "";    
189         }
190     }
191         
192     /**
193      * Deletes the local dwu logfile.
194      */
195     static void killLogFile () {
196         LOG_FILE.delete();    
197     }
198         
199     /**
200      * Returns a alphabetically (key-) sorted array of system properties. 
201      
202      @return String[] the sorted System Properties String array
203      */
204     
205     static String[] getSortetSysPropArray () {        
206         final List list = Arrays.asList(System.getProperties()
207                                               .keySet()
208                                               .toArray());
209         Collections.sort(list);                    
210         return (String[]) list.toArray(new String[0]);
211     }
212     
213     /**
214      * Sets a new Locale and creates a new ResourceBundle.
215      
216      @param locale the new locale
217      */
218     static void setLocale (final Locale locale) {
219         lang = ResourceBundle.getBundle ("l10n",
220                                          locale);        
221     }
222         
223     /**
224      * Localizes a given dictionary key into a readable string. If the key is
225      * unknown, it will be returned!
226      
227      @param key        a dictionary key
228      @return String    a localized string or, if unknown, the key
229      */
230     static String localize (final String key) {
231         try {
232             return (key.length() ? lang.getString(key"");
233         catch (java.util.MissingResourceException mre) {
234             // could not be localized; returning key
235             return key;
236         }
237     }
238 
239 
240     /**
241      * Sets the size of a window and centers it on screen.
242      *
243      @param window    the window object (a dialog, frame ...)
244      @param width     the preferred width
245      @param height    the preferred height
246      */
247     static void setSmartSize (final Window  window,
248                                 final int     width,
249                               final int     height) {
250         window.setSize(width, height);
251         window.setLocation((intToolkit.getDefaultToolkit()
252                                         .getScreenSize()
253                                         .getWidth()  - width  / 2,
254                            (intToolkit.getDefaultToolkit()
255                                         .getScreenSize()
256                                         .getHeight() - height / 2);
257     }     
258     
259     /*
260     HTMLEditorKit kit = new HTMLEditorKit();
261     MutableAttributeSet set = kit.getInputAttributes();
262     HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
263     StyleConstants.setFontSize( set, 14 );
264     doc.setCharacterAttributes( 0, doc.getLength(), set, false);
265    
266        schauen -> http://www.lightdev.com/dev/sh.htm
267     */
268         
269 }