KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > izforge > izpack > panels > PathInputPanel


1 /*
2  * IzPack - Copyright 2001-2007 Julien Ponge, All Rights Reserved.
3  *
4  * http://www.izforge.com/izpack/
5  * http://developer.berlios.de/projects/izpack/
6  *
7  * Copyright 2004 Klaus Bartz
8  *
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  * http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  */

21
22 package com.izforge.izpack.panels;
23
24 import java.awt.event.ActionEvent JavaDoc;
25 import java.awt.event.ActionListener JavaDoc;
26 import java.io.BufferedReader JavaDoc;
27 import java.io.File JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.io.InputStreamReader JavaDoc;
31
32 import com.izforge.izpack.gui.IzPanelLayout;
33 import com.izforge.izpack.installer.InstallData;
34 import com.izforge.izpack.installer.InstallerFrame;
35 import com.izforge.izpack.installer.IzPanel;
36 import com.izforge.izpack.installer.ResourceNotFoundException;
37 import com.izforge.izpack.util.AbstractUIHandler;
38 import com.izforge.izpack.util.Debug;
39 import com.izforge.izpack.util.IoHelper;
40 import com.izforge.izpack.util.OsVersion;
41 import com.izforge.izpack.util.VariableSubstitutor;
42
43 /**
44  * Base class for panels which asks for paths.
45  *
46  * @author Klaus Bartz
47  *
48  */

49 public class PathInputPanel extends IzPanel implements ActionListener JavaDoc
50 {
51
52     /**
53      *
54      */

55     private static final long serialVersionUID = 3257566217698292531L;
56
57     /** Flag whether the choosen path must exist or not */
58     protected boolean mustExist = false;
59
60     /** Files which should be exist */
61     protected String JavaDoc[] existFiles = null;
62
63     /** The path which was chosen */
64     // protected String chosenPath;
65
/** The path selection sub panel */
66     protected PathSelectionPanel pathSelectionPanel;
67
68     protected String JavaDoc emptyTargetMsg;
69
70     protected String JavaDoc warnMsg;
71
72     protected static String JavaDoc defaultInstallDir = null;
73
74     /**
75      * The constructor.
76      *
77      * @param parent The parent window.
78      * @param idata The installation data.
79      */

80     public PathInputPanel(InstallerFrame parent, InstallData idata)
81     {
82         super(parent, idata, new IzPanelLayout());
83         // Set default values
84
emptyTargetMsg = getI18nStringForClass("empty_target", "TargetPanel");
85         warnMsg = getI18nStringForClass("warn", "TargetPanel");
86          
87         String JavaDoc introText = getI18nStringForClass("extendedIntro", "PathInputPanel");
88         if (introText == null || introText.endsWith("extendedIntro")
89                 || introText.indexOf('$') > -1 )
90         {
91             introText = getI18nStringForClass("intro", "PathInputPanel");
92             if (introText == null || introText.endsWith("intro"))
93                 introText = "";
94         }
95         // Intro
96
// row 0 column 0
97
add(createMultiLineLabel(introText));
98         // Label for input
99
// row 1 column 0.
100
add(createLabel("info", "TargetPanel", "open",
101                 LEFT, true), NEXT_LINE);
102         // Create path selection components and add they to this panel.
103
pathSelectionPanel = new PathSelectionPanel(this, idata);
104         add(pathSelectionPanel, NEXT_LINE);
105         createLayoutBottom();
106         getLayoutHelper().completeLayout();
107         }
108     /**
109      * This method does nothing. It is called from ctor of PathInputPanel, to give in a derived
110      * class the possibility to add more components under the path input components.
111      */

112     public void createLayoutBottom()
113     {
114         // Derived classes implements additional elements.
115
}
116
117     /**
118      * Actions-handling method.
119      *
120      * @param e The event.
121      */

122     public void actionPerformed(ActionEvent JavaDoc e)
123     {
124         Object JavaDoc source = e.getSource();
125         if (source == pathSelectionPanel.getPathInputField())
126         {
127             parent.navigateNext();
128         }
129
130     }
131
132     /**
133      * Indicates wether the panel has been validated or not.
134      *
135      * @return Wether the panel has been validated or not.
136      */

137     public boolean isValidated()
138     {
139         String JavaDoc chosenPath = pathSelectionPanel.getPath();
140         boolean ok = true;
141
142         // We put a warning if the specified target is nameless
143
if (chosenPath.length() == 0)
144         {
145             if (isMustExist())
146             {
147                 emitError(parent.langpack.getString("installer.error"), parent.langpack
148                         .getString("PathInputPanel.required"));
149                 return false;
150             }
151             ok = emitWarning(parent.langpack.getString("installer.warning"), emptyTargetMsg);
152         }
153         if (!ok) return ok;
154
155         // Normalize the path
156
File JavaDoc path = new File JavaDoc(chosenPath).getAbsoluteFile();
157         chosenPath = path.toString();
158         pathSelectionPanel.setPath(chosenPath);
159         if (isMustExist())
160         {
161             if (!path.exists())
162             {
163                 emitError(parent.langpack.getString("installer.error"), parent.langpack
164                         .getString(getI18nStringForClass("required", "PathInputPanel")));
165                 return false;
166             }
167             if (!pathIsValid())
168             {
169                 emitError(parent.langpack.getString("installer.error"), parent.langpack
170                         .getString(getI18nStringForClass("notValid", "PathInputPanel")));
171                 return false;
172             }
173         }
174         else
175         {
176             // We assume, that we would install something into this dir
177
if (!isWriteable())
178             {
179                 emitError(parent.langpack.getString("installer.error"), getI18nStringForClass(
180                         "notwritable", "TargetPanel"));
181                 return false;
182             }
183             // We put a warning if the directory exists else we warn
184
// that it will be created
185
if (path.exists())
186             {
187                 int res = askQuestion(parent.langpack.getString("installer.warning"), warnMsg,
188                         AbstractUIHandler.CHOICES_YES_NO, AbstractUIHandler.ANSWER_YES);
189                 ok = res == AbstractUIHandler.ANSWER_YES;
190             }
191             else
192             {
193                 ok = this.emitNotificationFeedback(getI18nStringForClass("createdir", "TargetPanel") + "\n"
194                         + chosenPath);
195             
196             }
197         }
198         return ok;
199     }
200
201     /**
202      * Returns whether the chosen path is true or not. If existFiles are not null, the existence of
203      * it under the choosen path are detected. This method can be also implemented in derived
204      * classes to handle special verification of the path.
205      *
206      * @return true if existFiles are exist or not defined, else false
207      */

208     protected boolean pathIsValid()
209     {
210         if (existFiles == null) return true;
211         for (int i = 0; i < existFiles.length; ++i)
212         {
213             File JavaDoc path = new File JavaDoc(pathSelectionPanel.getPath(), existFiles[i]).getAbsoluteFile();
214             if (!path.exists()) return false;
215         }
216         return true;
217     }
218
219     /**
220      * Returns the must exist state.
221      *
222      * @return the must exist state
223      */

224     public boolean isMustExist()
225     {
226         return mustExist;
227     }
228
229     /**
230      * Sets the must exist state. If it is true, the path must exist.
231      *
232      * @param b must exist state
233      */

234     public void setMustExist(boolean b)
235     {
236         mustExist = b;
237     }
238
239     /**
240      * Returns the array of strings which are described the files which must exist.
241      *
242      * @return paths of files which must exist
243      */

244     public String JavaDoc[] getExistFiles()
245     {
246         return existFiles;
247     }
248
249     /**
250      * Sets the paths of files which must exist under the chosen path.
251      *
252      * @param strings paths of files which must exist under the chosen path
253      */

254     public void setExistFiles(String JavaDoc[] strings)
255     {
256         existFiles = strings;
257     }
258
259     /**
260      * Loads up the "dir" resource associated with TargetPanel. Acceptable dir resource names:
261      * <code>
262      * TargetPanel.dir.macosx
263      * TargetPanel.dir.mac
264      * TargetPanel.dir.windows
265      * TargetPanel.dir.unix
266      * TargetPanel.dir.xxx,
267      * where xxx is the lower case version of System.getProperty("os.name"),
268      * with any spaces replace with underscores
269      * TargetPanel.dir (generic that will be applied if none of above is found)
270      * </code>
271      * As with all IzPack resources, each the above ids should be associated with a separate
272      * filename, which is set in the install.xml file at compile time.
273      */

274     public static void loadDefaultInstallDir(InstallerFrame parentFrame, InstallData idata)
275     {
276         // Load only once ...
277
if (getDefaultInstallDir() != null) return;
278         BufferedReader JavaDoc br = null;
279         try
280         {
281             InputStream JavaDoc in = null;
282
283             if (OsVersion.IS_WINDOWS)
284             {
285                 try
286                 {
287                 in = parentFrame.getResource("TargetPanel.dir.windows");
288                 }
289                 catch (ResourceNotFoundException rnfe)
290                 {}//it's usual, that the resource does not exist
291
}
292             else if (OsVersion.IS_OSX)
293             {
294                 try
295                 {
296                 in = parentFrame.getResource("TargetPanel.dir.macosx");
297                 }
298                 catch (ResourceNotFoundException rnfe)
299                 {}//it's usual, that the resource does not exist
300
}
301             else
302             {
303                 String JavaDoc os = System.getProperty("os.name");
304                 // first try to look up by specific os name
305
os = os.replace(' ', '_'); // avoid spaces in file names
306
os = os.toLowerCase(); // for consistency among TargetPanel res
307
// files
308
try
309                 {
310                     in = parentFrame.getResource("TargetPanel.dir.".concat(os));
311                 }
312                 catch (ResourceNotFoundException rnfe)
313                 {}
314                 // if not specific os, try getting generic 'unix' resource file
315
if (in == null)
316                 {
317                     try
318                     {
319                         in = parentFrame.getResource("TargetPanel.dir.unix");
320                     }
321                     catch (ResourceNotFoundException eee)
322                     {}
323                 }
324
325             }
326
327             // if all above tests failed, there is no resource file,
328
// so use system default
329
if (in == null)
330             {
331                 try
332                 {
333                     in = parentFrame.getResource("TargetPanel.dir");
334                 }
335                 catch (ResourceNotFoundException eee)
336                 {}
337             }
338
339             if (in != null)
340             {
341                 // now read the file, once we've identified which one to read
342
InputStreamReader JavaDoc isr = new InputStreamReader JavaDoc(in);
343                 br = new BufferedReader JavaDoc(isr);
344                 String JavaDoc line;
345                 while ((line = br.readLine()) != null)
346                 {
347                     line = line.trim();
348                     // use the first non-blank line
349
if (!"".equals(line)) break;
350                 }
351                 defaultInstallDir = line;
352                 VariableSubstitutor vs = new VariableSubstitutor(idata.getVariables());
353                 defaultInstallDir = vs.substitute(defaultInstallDir, null);
354             }
355         }
356         catch (Exception JavaDoc e)
357         {
358             //mar: what's the common way to log an exception ?
359
e.printStackTrace();
360             defaultInstallDir = null;
361             // leave unset to take the system default set by Installer class
362
}
363         finally
364         {
365             try
366             {
367                 if (br != null) br.close();
368             }
369             catch (IOException JavaDoc ignored)
370             {}
371         }
372     }
373
374     /**
375      * This method determines whether the chosen dir is writeable or not.
376      *
377      * @return whether the chosen dir is writeable or not
378      */

379     public boolean isWriteable()
380     {
381         File JavaDoc existParent = IoHelper.existingParent(new File JavaDoc(pathSelectionPanel.getPath()));
382         if (existParent == null) return false;
383         // On windows we cannot use canWrite because
384
// it looks to the dos flags which are not valid
385
// on NT or 2k XP or ...
386
if (OsVersion.IS_WINDOWS)
387         {
388             File JavaDoc tmpFile;
389             try
390             {
391                 tmpFile = File.createTempFile("izWrTe", ".tmp", existParent);
392                 tmpFile.deleteOnExit();
393             }
394             catch (IOException JavaDoc e)
395             {
396                 Debug.trace(e.toString());
397                 return false;
398             }
399             return true;
400         }
401         return existParent.canWrite();
402     }
403
404     /**
405      * Returns the default for the installation directory.
406      *
407      * @return the default for the installation directory
408      */

409     public static String JavaDoc getDefaultInstallDir()
410     {
411         return defaultInstallDir;
412     }
413
414     /**
415      * Sets the default for the installation directory to the given string.
416      *
417      * @param string path for default for the installation directory
418      */

419     public static void setDefaultInstallDir(String JavaDoc string)
420     {
421         defaultInstallDir = string;
422     }
423
424 }
425
Popular Tags