KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jface > dialogs > DialogSettings


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.jface.dialogs;
12
13 import java.io.BufferedReader JavaDoc;
14 import java.io.FileInputStream JavaDoc;
15 import java.io.FileOutputStream JavaDoc;
16 import java.io.IOException JavaDoc;
17 import java.io.InputStreamReader JavaDoc;
18 import java.io.OutputStream JavaDoc;
19 import java.io.OutputStreamWriter JavaDoc;
20 import java.io.PrintWriter JavaDoc;
21 import java.io.Reader JavaDoc;
22 import java.io.UnsupportedEncodingException JavaDoc;
23 import java.io.Writer JavaDoc;
24 import java.util.ArrayList JavaDoc;
25 import java.util.Collection JavaDoc;
26 import java.util.Collections JavaDoc;
27 import java.util.Enumeration JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.Map JavaDoc;
32
33 import javax.xml.parsers.DocumentBuilder JavaDoc;
34 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
35 import javax.xml.parsers.ParserConfigurationException JavaDoc;
36
37 import org.w3c.dom.Document JavaDoc;
38 import org.w3c.dom.Element JavaDoc;
39 import org.w3c.dom.Node JavaDoc;
40 import org.w3c.dom.NodeList JavaDoc;
41 import org.xml.sax.InputSource JavaDoc;
42 import org.xml.sax.SAXException JavaDoc;
43
44 /**
45  * Concrete implementation of a dialog settings (<code>IDialogSettings</code>)
46  * using a hash table and XML. The dialog store can be read
47  * from and saved to a stream. All keys and values must be strings or array of
48  * strings. Primitive types are converted to strings.
49  * <p>
50  * This class was not designed to be subclassed.
51  *
52  * Here is an example of using a DialogSettings:
53  * </p>
54  * <pre>
55  * <code>
56  * DialogSettings settings = new DialogSettings("root");
57  * settings.put("Boolean1",true);
58  * settings.put("Long1",100);
59  * settings.put("Array1",new String[]{"aaaa1","bbbb1","cccc1"});
60  * DialogSettings section = new DialogSettings("sectionName");
61  * settings.addSection(section);
62  * section.put("Int2",200);
63  * section.put("Float2",1.1);
64  * section.put("Array2",new String[]{"aaaa2","bbbb2","cccc2"});
65  * settings.save("c:\\temp\\test\\dialog.xml");
66  * </code>
67  * </pre>
68  */

69
70 public class DialogSettings implements IDialogSettings {
71     // The name of the DialogSettings.
72
private String JavaDoc name;
73
74     /* A Map of DialogSettings representing each sections in a DialogSettings.
75      It maps the DialogSettings' name to the DialogSettings */

76     private Map JavaDoc sections;
77
78     /* A Map with all the keys and values of this sections.
79      Either the keys an values are restricted to strings. */

80     private Map JavaDoc items;
81
82     // A Map with all the keys mapped to array of strings.
83
private Map JavaDoc arrayItems;
84
85     private static final String JavaDoc TAG_SECTION = "section";//$NON-NLS-1$
86

87     private static final String JavaDoc TAG_NAME = "name";//$NON-NLS-1$
88

89     private static final String JavaDoc TAG_KEY = "key";//$NON-NLS-1$
90

91     private static final String JavaDoc TAG_VALUE = "value";//$NON-NLS-1$
92

93     private static final String JavaDoc TAG_LIST = "list";//$NON-NLS-1$
94

95     private static final String JavaDoc TAG_ITEM = "item";//$NON-NLS-1$
96

97     /**
98      * Create an empty dialog settings which loads and saves its
99      * content to a file.
100      * Use the methods <code>load(String)</code> and <code>store(String)</code>
101      * to load and store this dialog settings.
102      *
103      * @param sectionName the name of the section in the settings.
104      */

105     public DialogSettings(String JavaDoc sectionName) {
106         name = sectionName;
107         items = new HashMap JavaDoc();
108         arrayItems = new HashMap JavaDoc();
109         sections = new HashMap JavaDoc();
110     }
111
112     /* (non-Javadoc)
113      * Method declared on IDialogSettings.
114      */

115     public IDialogSettings addNewSection(String JavaDoc sectionName) {
116         DialogSettings section = new DialogSettings(sectionName);
117         addSection(section);
118         return section;
119     }
120
121     /* (non-Javadoc)
122      * Method declared on IDialogSettings.
123      */

124     public void addSection(IDialogSettings section) {
125         sections.put(section.getName(), section);
126     }
127
128     /* (non-Javadoc)
129      * Method declared on IDialogSettings.
130      */

131     public String JavaDoc get(String JavaDoc key) {
132         return (String JavaDoc) items.get(key);
133     }
134
135     /* (non-Javadoc)
136      * Method declared on IDialogSettings.
137      */

138     public String JavaDoc[] getArray(String JavaDoc key) {
139         return (String JavaDoc[]) arrayItems.get(key);
140     }
141
142     /* (non-Javadoc)
143      * Method declared on IDialogSettings.
144      */

145     public boolean getBoolean(String JavaDoc key) {
146         return Boolean.valueOf((String JavaDoc) items.get(key)).booleanValue();
147     }
148
149     /* (non-Javadoc)
150      * Method declared on IDialogSettings.
151      */

152     public double getDouble(String JavaDoc key) throws NumberFormatException JavaDoc {
153         String JavaDoc setting = (String JavaDoc) items.get(key);
154         if (setting == null) {
155             throw new NumberFormatException JavaDoc(
156                     "There is no setting associated with the key \"" + key + "\"");//$NON-NLS-1$ //$NON-NLS-2$
157
}
158
159         return new Double JavaDoc(setting).doubleValue();
160     }
161
162     /* (non-Javadoc)
163      * Method declared on IDialogSettings.
164      */

165     public float getFloat(String JavaDoc key) throws NumberFormatException JavaDoc {
166         String JavaDoc setting = (String JavaDoc) items.get(key);
167         if (setting == null) {
168             throw new NumberFormatException JavaDoc(
169                     "There is no setting associated with the key \"" + key + "\"");//$NON-NLS-1$ //$NON-NLS-2$
170
}
171
172         return new Float JavaDoc(setting).floatValue();
173     }
174
175     /* (non-Javadoc)
176      * Method declared on IDialogSettings.
177      */

178     public int getInt(String JavaDoc key) throws NumberFormatException JavaDoc {
179         String JavaDoc setting = (String JavaDoc) items.get(key);
180         if (setting == null) {
181             //new Integer(null) will throw a NumberFormatException and meet our spec, but this message
182
//is clearer.
183
throw new NumberFormatException JavaDoc(
184                     "There is no setting associated with the key \"" + key + "\"");//$NON-NLS-1$ //$NON-NLS-2$
185
}
186
187         return new Integer JavaDoc(setting).intValue();
188     }
189
190     /* (non-Javadoc)
191      * Method declared on IDialogSettings.
192      */

193     public long getLong(String JavaDoc key) throws NumberFormatException JavaDoc {
194         String JavaDoc setting = (String JavaDoc) items.get(key);
195         if (setting == null) {
196             //new Long(null) will throw a NumberFormatException and meet our spec, but this message
197
//is clearer.
198
throw new NumberFormatException JavaDoc(
199                     "There is no setting associated with the key \"" + key + "\"");//$NON-NLS-1$ //$NON-NLS-2$
200
}
201
202         return new Long JavaDoc(setting).longValue();
203     }
204
205     /* (non-Javadoc)
206      * Method declared on IDialogSettings.
207      */

208     public String JavaDoc getName() {
209         return name;
210     }
211
212     /* (non-Javadoc)
213      * Method declared on IDialogSettings.
214      */

215     public IDialogSettings getSection(String JavaDoc sectionName) {
216         return (IDialogSettings) sections.get(sectionName);
217     }
218
219     /* (non-Javadoc)
220      * Method declared on IDialogSettings.
221      */

222     public IDialogSettings[] getSections() {
223         Collection JavaDoc values = sections.values();
224         DialogSettings[] result = new DialogSettings[values.size()];
225         values.toArray(result);
226         return result;
227     }
228
229     /* (non-Javadoc)
230      * Method declared on IDialogSettings.
231      */

232     public void load(Reader JavaDoc r) {
233         Document JavaDoc document = null;
234         try {
235             DocumentBuilder JavaDoc parser = DocumentBuilderFactory.newInstance()
236                     .newDocumentBuilder();
237             // parser.setProcessNamespace(true);
238
document = parser.parse(new InputSource JavaDoc(r));
239
240             //Strip out any comments first
241
Node JavaDoc root = document.getFirstChild();
242             while (root.getNodeType() == Node.COMMENT_NODE) {
243                 document.removeChild(root);
244                 root = document.getFirstChild();
245             }
246             load(document, (Element JavaDoc) root);
247         } catch (ParserConfigurationException JavaDoc e) {
248             // ignore
249
} catch (IOException JavaDoc e) {
250             // ignore
251
} catch (SAXException JavaDoc e) {
252             // ignore
253
}
254     }
255
256     /* (non-Javadoc)
257      * Method declared on IDialogSettings.
258      */

259     public void load(String JavaDoc fileName) throws IOException JavaDoc {
260         FileInputStream JavaDoc stream = new FileInputStream JavaDoc(fileName);
261         BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(
262                 stream, "utf-8"));//$NON-NLS-1$
263
load(reader);
264         reader.close();
265     }
266
267     /* (non-Javadoc)
268      * Load the setting from the <code>document</code>
269      */

270     private void load(Document JavaDoc document, Element JavaDoc root) {
271         name = root.getAttribute(TAG_NAME);
272         NodeList JavaDoc l = root.getElementsByTagName(TAG_ITEM);
273         for (int i = 0; i < l.getLength(); i++) {
274             Node JavaDoc n = l.item(i);
275             if (root == n.getParentNode()) {
276                 String JavaDoc key = ((Element JavaDoc) l.item(i)).getAttribute(TAG_KEY);
277                 String JavaDoc value = ((Element JavaDoc) l.item(i)).getAttribute(TAG_VALUE);
278                 items.put(key, value);
279             }
280         }
281         l = root.getElementsByTagName(TAG_LIST);
282         for (int i = 0; i < l.getLength(); i++) {
283             Node JavaDoc n = l.item(i);
284             if (root == n.getParentNode()) {
285                 Element JavaDoc child = (Element JavaDoc) l.item(i);
286                 String JavaDoc key = child.getAttribute(TAG_KEY);
287                 NodeList JavaDoc list = child.getElementsByTagName(TAG_ITEM);
288                 List JavaDoc valueList = new ArrayList JavaDoc();
289                 for (int j = 0; j < list.getLength(); j++) {
290                     Element JavaDoc node = (Element JavaDoc) list.item(j);
291                     if (child == node.getParentNode()) {
292                         valueList.add(node.getAttribute(TAG_VALUE));
293                     }
294                 }
295                 String JavaDoc[] value = new String JavaDoc[valueList.size()];
296                 valueList.toArray(value);
297                 arrayItems.put(key, value);
298             }
299         }
300         l = root.getElementsByTagName(TAG_SECTION);
301         for (int i = 0; i < l.getLength(); i++) {
302             Node JavaDoc n = l.item(i);
303             if (root == n.getParentNode()) {
304                 DialogSettings s = new DialogSettings("NoName");//$NON-NLS-1$
305
s.load(document, (Element JavaDoc) n);
306                 addSection(s);
307             }
308         }
309     }
310
311     /* (non-Javadoc)
312      * Method declared on IDialogSettings.
313      */

314     public void put(String JavaDoc key, String JavaDoc[] value) {
315         arrayItems.put(key, value);
316     }
317
318     /* (non-Javadoc)
319      * Method declared on IDialogSettings.
320      */

321     public void put(String JavaDoc key, double value) {
322         put(key, String.valueOf(value));
323     }
324
325     /* (non-Javadoc)
326      * Method declared on IDialogSettings.
327      */

328     public void put(String JavaDoc key, float value) {
329         put(key, String.valueOf(value));
330     }
331
332     /* (non-Javadoc)
333      * Method declared on IDialogSettings.
334      */

335     public void put(String JavaDoc key, int value) {
336         put(key, String.valueOf(value));
337     }
338
339     /* (non-Javadoc)
340      * Method declared on IDialogSettings.
341      */

342     public void put(String JavaDoc key, long value) {
343         put(key, String.valueOf(value));
344     }
345
346     /* (non-Javadoc)
347      * Method declared on IDialogSettings.
348      */

349     public void put(String JavaDoc key, String JavaDoc value) {
350         items.put(key, value);
351     }
352
353     /* (non-Javadoc)
354      * Method declared on IDialogSettings.
355      */

356     public void put(String JavaDoc key, boolean value) {
357         put(key, String.valueOf(value));
358     }
359
360     /* (non-Javadoc)
361      * Method declared on IDialogSettings.
362      */

363     public void save(Writer JavaDoc writer) throws IOException JavaDoc {
364         save(new XMLWriter(writer));
365     }
366
367     /* (non-Javadoc)
368      * Method declared on IDialogSettings.
369      */

370     public void save(String JavaDoc fileName) throws IOException JavaDoc {
371         FileOutputStream JavaDoc stream = new FileOutputStream JavaDoc(fileName);
372         XMLWriter writer = new XMLWriter(stream);
373         save(writer);
374         writer.close();
375     }
376
377     /* (non-Javadoc)
378      * Save the settings in the <code>document</code>.
379      */

380     private void save(XMLWriter out) {
381         HashMap JavaDoc attributes = new HashMap JavaDoc(2);
382         attributes.put(TAG_NAME, name == null ? "" : name); //$NON-NLS-1$
383
out.startTag(TAG_SECTION, attributes);
384         attributes.clear();
385
386         for (Iterator JavaDoc i = items.keySet().iterator(); i.hasNext();) {
387             String JavaDoc key = (String JavaDoc) i.next();
388             attributes.put(TAG_KEY, key == null ? "" : key); //$NON-NLS-1$
389
String JavaDoc string = (String JavaDoc) items.get(key);
390             attributes.put(TAG_VALUE, string == null ? "" : string); //$NON-NLS-1$
391
out.printTag(TAG_ITEM, attributes, true);
392         }
393
394         attributes.clear();
395         for (Iterator JavaDoc i = arrayItems.keySet().iterator(); i.hasNext();) {
396             String JavaDoc key = (String JavaDoc) i.next();
397             attributes.put(TAG_KEY, key == null ? "" : key); //$NON-NLS-1$
398
out.startTag(TAG_LIST, attributes);
399             String JavaDoc[] value = (String JavaDoc[]) arrayItems.get(key);
400             attributes.clear();
401             if (value != null) {
402                 for (int index = 0; index < value.length; index++) {
403                     String JavaDoc string = value[index];
404                     attributes.put(TAG_VALUE, string == null ? "" : string); //$NON-NLS-1$
405
out.printTag(TAG_ITEM, attributes, true);
406                 }
407             }
408             out.endTag(TAG_LIST);
409             attributes.clear();
410         }
411         for (Iterator JavaDoc i = sections.values().iterator(); i.hasNext();) {
412             ((DialogSettings) i.next()).save(out);
413         }
414         out.endTag(TAG_SECTION);
415     }
416     
417     /**
418      * A simple XML writer. Using this instead of the javax.xml.transform classes allows
419      * compilation against JCL Foundation (bug 80059).
420      */

421     private static class XMLWriter extends PrintWriter JavaDoc {
422         /** current number of tabs to use for ident */
423         protected int tab;
424
425         /** the xml header */
426         protected static final String JavaDoc XML_VERSION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; //$NON-NLS-1$
427

428         /**
429          * Create a new XMLWriter
430          * @param output the stream to write the output to
431          * @throws UnsupportedEncodingException thrown if charset is not supported
432          */

433         public XMLWriter(OutputStream JavaDoc output) throws UnsupportedEncodingException JavaDoc {
434             super(new OutputStreamWriter JavaDoc(output, "UTF8")); //$NON-NLS-1$
435
tab = 0;
436             println(XML_VERSION);
437         }
438
439         /**
440          * Create a new XMLWriter
441          * @param output the write to used when writing to
442          */

443         public XMLWriter(Writer JavaDoc output) {
444             super(output);
445             tab = 0;
446             println(XML_VERSION);
447         }
448
449         /**
450          * write the intended end tag
451          * @param name the name of the tag to end
452          */

453         public void endTag(String JavaDoc name) {
454             tab--;
455             printTag("/" + name, null, false); //$NON-NLS-1$
456
}
457
458         private void printTabulation() {
459             for (int i = 0; i < tab; i++) {
460                 super.print('\t');
461             }
462         }
463
464         /**
465          * write the tag to the stream and format it by itending it and add new line after the tag
466          * @param name the name of the tag
467          * @param parameters map of parameters
468          * @param close should the tag be ended automatically (=> empty tag)
469          */

470         public void printTag(String JavaDoc name, HashMap JavaDoc parameters, boolean close) {
471             printTag(name, parameters, true, true, close);
472         }
473
474         private void printTag(String JavaDoc name, HashMap JavaDoc parameters, boolean shouldTab, boolean newLine, boolean close) {
475             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
476             sb.append('<');
477             sb.append(name);
478             if (parameters != null) {
479                 for (Enumeration JavaDoc e = Collections.enumeration(parameters.keySet()); e.hasMoreElements();) {
480                     sb.append(" "); //$NON-NLS-1$
481
String JavaDoc key = (String JavaDoc) e.nextElement();
482                     sb.append(key);
483                     sb.append("=\""); //$NON-NLS-1$
484
sb.append(getEscaped(String.valueOf(parameters.get(key))));
485                     sb.append("\""); //$NON-NLS-1$
486
}
487             }
488             if (close) {
489                 sb.append('/');
490             }
491             sb.append('>');
492             if (shouldTab) {
493                 printTabulation();
494             }
495             if (newLine) {
496                 println(sb.toString());
497             } else {
498                 print(sb.toString());
499             }
500         }
501
502         /**
503          * start the tag
504          * @param name the name of the tag
505          * @param parameters map of parameters
506          */

507         public void startTag(String JavaDoc name, HashMap JavaDoc parameters) {
508             startTag(name, parameters, true);
509             tab++;
510         }
511
512         private void startTag(String JavaDoc name, HashMap JavaDoc parameters, boolean newLine) {
513             printTag(name, parameters, true, newLine, false);
514         }
515
516         private static void appendEscapedChar(StringBuffer JavaDoc buffer, char c) {
517             String JavaDoc replacement = getReplacement(c);
518             if (replacement != null) {
519                 buffer.append('&');
520                 buffer.append(replacement);
521                 buffer.append(';');
522             } else {
523                 buffer.append(c);
524             }
525         }
526
527         private static String JavaDoc getEscaped(String JavaDoc s) {
528             StringBuffer JavaDoc result = new StringBuffer JavaDoc(s.length() + 10);
529             for (int i = 0; i < s.length(); ++i) {
530                 appendEscapedChar(result, s.charAt(i));
531             }
532             return result.toString();
533         }
534
535         private static String JavaDoc getReplacement(char c) {
536             // Encode special XML characters into the equivalent character references.
537
// The first five are defined by default for all XML documents.
538
// The next three (#xD, #xA, #x9) are encoded to avoid them
539
// being converted to spaces on deserialization
540
switch (c) {
541                 case '<' :
542                     return "lt"; //$NON-NLS-1$
543
case '>' :
544                     return "gt"; //$NON-NLS-1$
545
case '"' :
546                     return "quot"; //$NON-NLS-1$
547
case '\'' :
548                     return "apos"; //$NON-NLS-1$
549
case '&' :
550                     return "amp"; //$NON-NLS-1$
551
case '\r':
552                     return "#x0D"; //$NON-NLS-1$
553
case '\n':
554                     return "#x0A"; //$NON-NLS-1$
555
case '\u0009':
556                     return "#x09"; //$NON-NLS-1$
557
}
558             return null;
559         }
560     }
561 }
562
Popular Tags