Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: com/sshtools/apps/PreferencesStore.java


1   /**
2    *   Sshtools - Applications
3    *
4    *   Copyright (C) 2002 Lee David Painter
5    *
6    *   Written by: 2002 Brett Smith <t_magicthize@users.sourceforge.net>
7    *
8    *   This program is free software; you can redistribute it and/or modify
9    *   it under the terms of the GNU General Public License as published by
10   *   the Free Software Foundation; either version 2 of the License, or
11   *   (at your option) any later version.
12   *
13   *   This program is distributed in the hope that it will be useful,
14   *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   *   GNU General Public License for more details.
17   *
18   *   You should have received a copy of the GNU General Public License
19   *   along with this program; if not, write to the Free Software
20   *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21   */
22  package com.sshtools.apps;
23  
24  import javax.swing.*;
25  import java.awt.*;
26  import java.io.*;
27  import java.awt.event.*;
28  import java.util.*;
29  import java.net.URL;
30  import com.sshtools.j2ssh.ui.ResourceIcon;
31  import com.sshtools.j2ssh.ui.UIUtil;
32  
33  import org.apache.log4j.*;
34  
35  /**
36   *  <p>Provides a backing store for preferences using a simple properties
37   *  file. The <code>init</code> method must be called first providing the
38   *  file to store the preferences in.</p>
39   *
40   *@author     Brett Smith (<A HREF="mailto:t_magicthize@users.sourceforge.net">
41   *                          t_magicthize@users.sourceforge.net</A> )
42   *@created    12 January 2002
43   *@version    $Id: PreferencesStore.java,v 1.2 2003/01/14 01:04:07 t_magicthize Exp $
44   */
45  
46  public class PreferencesStore {
47  
48      protected static Logger log = Logger.getLogger(PreferencesStore.class);
49  
50      /**  Save table column positions and sizes. Note, the table must have its
51       *   auto resize mode set to off, i.e.
52       *
53       *   @param table tabl
54       *   @param pref preference name
55       */
56      public static void saveTableMetrics(JTable table,
57                                          String pref) {
58          for(int i = 0 ; i < table.getColumnModel().getColumnCount() ; i ++) {
59              int w = table.getColumnModel().getColumn(i).getWidth();
60              put(pref + ".column." + i + ".width", String.valueOf(w));
61              put(pref + ".column." + i + ".position", String.valueOf(
62                          table.convertColumnIndexToModel(i)));
63          }
64      }
65  
66      /**  Restore table column positions and sizes. Note, the table must have its
67       *   auto resize mode set to off, i.e.
68       *
69       *   @param table
70       *   @param pref preferences
71       *   @param defaultWidths default column widths
72       */
73      public static void restoreTableMetrics(JTable table,
74                                             String pref,
75                                             int[] defaultWidths) {
76      //  Check the table columns may be resized correctly
77          if(table.getAutoResizeMode() != JTable.AUTO_RESIZE_OFF)
78              throw new IllegalArgumentException(
79                  "Table AutoResizeMode must be JTable.AUTO_RESIZE_OFF");
80  
81      //  Restore the table column widths and positions
82          for(int i = 0 ; i < table.getColumnModel().getColumnCount() ; i ++) {
83              try {
84                  table.moveColumn(table.convertColumnIndexToView(getInt(pref +
85                          ".column." + i + ".position", i)), i);
86                  table.getColumnModel().getColumn(i).setPreferredWidth(
87                      getInt(pref + ".column." + i + ".width",
88                      defaultWidths == null ?
89                      table.getColumnModel().getColumn(i).getPreferredWidth() :
90                      defaultWidths[i]));
91              }
92              catch(NumberFormatException nfe) {
93              }
94          }
95      }
96  
97      /**
98       * Return if the preferences store is available. This will be <code>false</code
99       * if the file could not be opened or created for some reason.
100      *
101      * @return store available
102      */
103     public static boolean isStoreAvailable() {
104         return storeAvailable;
105     }
106 
107     /**
108      * Initialise the preferences store. The file provided will be created
109      * if it doesn't exist (as will any requires parent directories)
110      *
111      * @param file file where preferences are to be kept.
112      */
113     public static void init(File file) {
114         PreferencesStore.file = file;
115 
116     //  Make sure the preferences directory exists, creating it if it doesn't
117         File dir = file.getParentFile();
118         if(!dir.exists()) {
119             log.info("Creating SSHTerm preferences directory " +
120                 dir.getAbsolutePath());
121             if(!dir.mkdirs())
122                 log.error("Preferences directory " +
123                     dir.getAbsolutePath() + " could not be created. " +
124                     "Preferences will not be stored");
125         }
126         storeAvailable = dir.exists();
127 
128     //  If the preferences file exists, then load it
129         if(storeAvailable) {
130             if(file.exists()) {
131                 InputStream in = null;
132                 try {
133                     in = new FileInputStream(file);
134                     preferences.load(in);
135                     storeAvailable = true;
136                 }
137                 catch(IOException ioe) {
138                     log.error(ioe);
139                 }
140                 finally {
141                     if(in != null) {
142                         try {
143                             in.close();
144                         }
145                         catch(IOException ioe) {
146                         }
147                     }
148                 }
149             }
150     //  Otherwise create it
151             else {
152                 savePreferences();
153             }
154         }
155     }
156 
157     /**
158      * Save the preferences, creating the file if required.
159      */
160 
161     public static void savePreferences() {
162         if(file == null)
163             log.error("Preferences not saved as PreferencesStore has not been initialise.");
164         else {
165             OutputStream out = null;
166             try {
167                 out = new FileOutputStream(file);
168                 preferences.store(out, "SSHTerm preferences");
169                 log.info("Preferences written to " +
170                     file.getAbsolutePath() );
171                 storeAvailable = true;
172             }
173             catch(IOException ioe) {
174                 log.error(ioe);
175             }
176             finally {
177                 if(out != null) {
178                     try {
179                         out.close();
180                     }
181                     catch(IOException ioe) {
182                     }
183                 }
184             }
185         }
186     }
187 
188     /**
189      * Return a string preference
190      *
191      * @param name name of preference
192      * @param def default value if no preference is found
193      * @return value
194      */
195     public static String get(String name, String def) {
196         return preferences.getProperty(name, def);
197     };
198 
199     /**
200      * Store a string preference
201      *
202      * @param name name of preference
203      * @param val value of preference
204      */
205     public static void put(String name, String val) {
206         preferences.put(name, val);
207     }
208 
209     /**
210      * Return a <code>Rectangle</code> preference
211      *
212      * @param name name of preference
213      * @param def default value if no preference is found
214      * @return value
215      */
216     public static Rectangle getRectangle(String name, Rectangle def) {
217         String s = preferences.getProperty(name);
218         if(s == null || s.equals(""))
219             return def;
220         else {
221             StringTokenizer st = new StringTokenizer(s, ",");
222             Rectangle r = new Rectangle();
223             try {
224                 r.x = Integer.parseInt(st.nextToken());
225                 r.y = Integer.parseInt(st.nextToken());
226                 r.width = Integer.parseInt(st.nextToken());
227                 r.height = Integer.parseInt(st.nextToken());
228             }
229             catch(NumberFormatException nfe) {
230                 log.warn("Preference is " + name +
231                     " is badly formatted", nfe);
232             }
233             return r;
234         }
235     }
236 
237     /**
238      * Store a rectangle preference
239      *
240      * @param name name of preference
241      * @param val value of preference
242      */
243     public static void putRectangle(String name, Rectangle val) {
244         preferences.put(name, val == null ? "" : (
245             val.x + "," + val.y + "," + val.width + "," + val.height ) );
246     }
247 
248     /**
249      * Return a integer preference
250      *
251      * @param name name of preference
252      * @param def default value if no preference is found
253      * @return value
254      */
255     public static int getInt(String name, int def) {
256         String s = preferences.getProperty(name);
257         if(s != null && !s.equals("")) {
258             try {
259                 return Integer.parseInt(s);
260             }
261             catch(NumberFormatException nfe) {
262                 log.warn("Preference is " + name +
263                     " is badly formatted", nfe);
264             }
265         }
266         return def;
267     }
268 
269     /**
270      * Store a integer preference
271      *
272      * @param name name of preference
273      * @param val value of preference
274      */
275     public static void putInt(String name, int val) {
276         preferences.put(name, String.valueOf(val));
277     }
278 
279     /**
280      * Return a boolean preference
281      *
282      * @param name name of preference
283      * @param def default value if no preference is found
284      * @return value
285      */
286 
287     public static boolean getBoolean(String name, boolean def) {
288         return get(name, String.valueOf(def)).equals("true");
289     }
290 
291     /**
292      * Store a boolean preference
293      *
294      * @param name name of preference
295      * @param val value of preference
296      */
297 
298     public static void putBoolean(String name, boolean val) {
299         preferences.put(name, String.valueOf(val));
300     }
301 
302     /**
303      * Determine if a preference exists
304      *
305      * @param name name of preference
306      * @return exists
307      */
308     public static boolean preferenceExists(String name) {
309         return preferences.containsKey(name);
310     }
311 
312     //
313 
314     private static File file;
315     private static boolean storeAvailable;
316     private static Properties preferences;
317 
318     //  Intialise the preferences
319     static
320     {
321         preferences = new Properties();
322     }
323 }