KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > help > internal > workingset > WorkingSetManager


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.help.internal.workingset;
12
13 import java.io.File 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.util.ArrayList JavaDoc;
19 import java.util.Iterator JavaDoc;
20 import java.util.List JavaDoc;
21 import java.util.SortedSet JavaDoc;
22 import java.util.TreeSet JavaDoc;
23
24 import javax.xml.parsers.DocumentBuilder JavaDoc;
25 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
26 import javax.xml.parsers.ParserConfigurationException JavaDoc;
27 import javax.xml.transform.OutputKeys JavaDoc;
28 import javax.xml.transform.Transformer JavaDoc;
29 import javax.xml.transform.TransformerException JavaDoc;
30 import javax.xml.transform.TransformerFactory JavaDoc;
31 import javax.xml.transform.dom.DOMSource JavaDoc;
32 import javax.xml.transform.stream.StreamResult JavaDoc;
33
34 import org.eclipse.core.runtime.IAdaptable;
35 import org.eclipse.core.runtime.IPath;
36 import org.eclipse.core.runtime.Platform;
37 import org.eclipse.help.internal.HelpPlugin;
38 import org.eclipse.help.internal.base.BaseHelpSystem;
39 import org.eclipse.help.internal.base.HelpBasePlugin;
40 import org.w3c.dom.Document JavaDoc;
41 import org.w3c.dom.Element JavaDoc;
42 import org.w3c.dom.Node JavaDoc;
43 import org.w3c.dom.NodeList JavaDoc;
44 import org.xml.sax.InputSource JavaDoc;
45 import org.xml.sax.SAXException JavaDoc;
46
47 /**
48  * The working set manager stores help working sets. Working sets are persisted
49  * whenever one is added or removed.
50  *
51  * @since 2.1
52  */

53 public class WorkingSetManager implements IHelpWorkingSetManager {
54
55     // Working set persistence
56
private static final String JavaDoc WORKING_SET_STATE_FILENAME = "workingsets.xml"; //$NON-NLS-1$
57

58     private SortedSet JavaDoc workingSets = new TreeSet JavaDoc(new WorkingSetComparator());
59
60     private AdaptableTocsArray root;
61
62     private static final DocumentBuilderFactory JavaDoc documentBuilderFactory = DocumentBuilderFactory
63             .newInstance();
64
65     private static final TransformerFactory JavaDoc transformerFactory = TransformerFactory
66             .newInstance();
67
68     /**
69      * Constructor
70      */

71     public WorkingSetManager() {
72         restoreState();
73     }
74
75     public AdaptableTocsArray getRoot() {
76         if (root == null)
77             root = new AdaptableTocsArray(HelpPlugin.getTocManager().getTocs(
78                     Platform.getNL()));
79         return root;
80     }
81
82     /**
83      * Adds a new working set and saves it
84      */

85     public void addWorkingSet(WorkingSet workingSet) {
86         if (workingSet == null || workingSets.contains(workingSet))
87             return;
88         workingSets.add(workingSet);
89         saveState();
90     }
91
92     /**
93      * Creates a new working set
94      */

95     public WorkingSet createWorkingSet(String JavaDoc name,
96             AdaptableHelpResource[] elements) {
97         return new WorkingSet(name, elements);
98     }
99
100     /**
101      * Tests the receiver and the object for equality
102      *
103      * @param object
104      * object to compare the receiver to
105      * @return true=the object equals the receiver, it has the same working
106      * sets. false otherwise
107      */

108     public boolean equals(Object JavaDoc object) {
109         if (this == object) {
110             return true;
111         }
112         if (object instanceof WorkingSetManager) {
113             WorkingSetManager workingSetManager = (WorkingSetManager) object;
114             return workingSetManager.workingSets.equals(workingSets);
115         }
116         return false;
117     }
118
119     /**
120      * Returns a working set by name
121      *
122      */

123     public WorkingSet getWorkingSet(String JavaDoc name) {
124         if (name == null || workingSets == null)
125             return null;
126
127         Iterator JavaDoc iter = workingSets.iterator();
128         while (iter.hasNext()) {
129             WorkingSet workingSet = (WorkingSet) iter.next();
130             if (name.equals(workingSet.getName()))
131                 return workingSet;
132         }
133         return null;
134     }
135
136     /**
137      * Returns the hash code.
138      *
139      * @return the hash code.
140      */

141     public int hashCode() {
142         return workingSets.hashCode();
143     }
144
145     /**
146      * Implements IWorkingSetManager.
147      *
148      * @see org.eclipse.ui.IWorkingSetManager#getWorkingSets()
149      */

150     public WorkingSet[] getWorkingSets() {
151         return (WorkingSet[]) workingSets.toArray(new WorkingSet[workingSets
152                 .size()]);
153     }
154
155     /**
156      * Returns the file used as the persistence store
157      *
158      * @return the file used as the persistence store
159      */

160     private File JavaDoc getWorkingSetStateFile() {
161         IPath path = HelpBasePlugin.getDefault().getStateLocation();
162         path = path.append(WORKING_SET_STATE_FILENAME);
163         return path.toFile();
164     }
165
166     /**
167      * Removes specified working set
168      */

169     public void removeWorkingSet(WorkingSet workingSet) {
170         workingSets.remove(workingSet);
171         saveState();
172     }
173
174     /**
175      * Reads the persistence store and creates the working sets stored in it.
176      */

177     public boolean restoreState() {
178         File JavaDoc stateFile = getWorkingSetStateFile();
179
180         if (stateFile.exists()) {
181             try {
182                 FileInputStream JavaDoc input = new FileInputStream JavaDoc(stateFile);
183                 InputStreamReader JavaDoc reader = new InputStreamReader JavaDoc(input, "utf-8"); //$NON-NLS-1$
184

185                 InputSource JavaDoc inputSource = new InputSource JavaDoc(reader);
186                 inputSource.setSystemId(stateFile.toString());
187
188                 DocumentBuilder JavaDoc parser = documentBuilderFactory
189                         .newDocumentBuilder();
190                 Document JavaDoc d = parser.parse(inputSource);
191
192                 Element JavaDoc rootElement = d.getDocumentElement();
193                 restoreWorkingSetState(rootElement);
194                 input.close();
195
196                 return true;
197             } catch (ParserConfigurationException JavaDoc pce) {
198                 HelpPlugin
199                         .logError(
200                                 "DocumentBuilder implementation could not be loaded, to restore working set state.", pce); //$NON-NLS-1$
201
return false;
202             } catch (SAXException JavaDoc se) {
203                 HelpBasePlugin
204                         .logError(
205                                 "Error occurred parsing file " + stateFile.toString() + ", while restoring working set state.", se); //$NON-NLS-1$ //$NON-NLS-2$
206
return false;
207             } catch (IOException JavaDoc ioe) {
208                 HelpBasePlugin
209                         .logError(
210                                 "Error occurred parsing file " + stateFile.toString() + ", while restoring working set state.", ioe); //$NON-NLS-1$ //$NON-NLS-2$
211
return false;
212             }
213         }
214         return false;
215     }
216
217     /**
218      * Recreates all working sets from the persistence store and adds them to
219      * the receiver.
220      *
221      * @param parent
222      * the xml element containing serialized working sets
223      */

224     private void restoreWorkingSetState(Element JavaDoc parent) {
225         NodeList JavaDoc workingSets = parent.getChildNodes();
226
227         for (int i = 0; i < workingSets.getLength(); i++) {
228             if (workingSets.item(i).getNodeType() != Node.ELEMENT_NODE)
229                 continue;
230
231             WorkingSet workingSet = restoreWorkingSet((Element JavaDoc) workingSets
232                     .item(i));
233             if (workingSet != null) {
234                 this.workingSets.add(workingSet);
235             }
236         }
237     }
238
239     /**
240      * Recreates a working set from the persistence store.
241      *
242      * @return the working set created from the memento or null if creation
243      * failed.
244      */

245     private WorkingSet restoreWorkingSet(Element JavaDoc workingSetNode) {
246
247         String JavaDoc name = workingSetNode.getAttribute("name"); //$NON-NLS-1$
248
NodeList JavaDoc items = workingSetNode.getElementsByTagName("item"); //$NON-NLS-1$
249
List JavaDoc helpResources = new ArrayList JavaDoc(items.getLength());
250         for (int i = 0; i < items.getLength(); i++) {
251             Element JavaDoc item = (Element JavaDoc) items.item(i);
252             String JavaDoc href = item.getAttribute("toc"); //$NON-NLS-1$
253
if (href == null || href.length() == 0)
254                 continue;
255
256             String JavaDoc child_pos = item.getAttribute("topic"); //$NON-NLS-1$
257
int pos = -1;
258             if (child_pos != null) {
259                 try {
260                     pos = Integer.parseInt(child_pos);
261                 } catch (Exception JavaDoc e) {
262                 }
263             }
264
265             AdaptableHelpResource toc = getAdaptableToc(href);
266
267             if (toc == null)
268                 return null;
269
270             if (pos == -1) {
271                 // Create the adaptable toc.
272
helpResources.add(toc);
273             } else {
274                 // Create the adaptable topic
275
AdaptableTopic[] topics = (AdaptableTopic[]) toc.getChildren();
276                 if (pos >= 0 && topics.length > pos)
277                     helpResources.add(topics[pos]);
278             }
279         }
280
281         AdaptableHelpResource[] elements = new AdaptableHelpResource[helpResources
282                 .size()];
283         helpResources.toArray(elements);
284
285         WorkingSet ws = createWorkingSet(name, elements);
286
287         return ws;
288     }
289
290     /**
291      * Saves the working sets in the persistence store
292      */

293     public synchronized boolean saveState() {
294         File JavaDoc stateFile = null;
295         try {
296             DocumentBuilder JavaDoc docBuilder = documentBuilderFactory
297                     .newDocumentBuilder();
298             Document JavaDoc doc = docBuilder.newDocument();
299             Element JavaDoc rootElement = doc.createElement("workingSets"); //$NON-NLS-1$
300
doc.appendChild(rootElement);
301
302             saveWorkingSetState(rootElement);
303
304             stateFile = getWorkingSetStateFile();
305             stateFile.getParentFile().mkdir();
306             FileOutputStream JavaDoc stream = new FileOutputStream JavaDoc(stateFile);
307
308             Transformer JavaDoc transformer = transformerFactory.newTransformer();
309             transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
310
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
311
DOMSource JavaDoc source = new DOMSource JavaDoc(doc);
312             StreamResult JavaDoc result = new StreamResult JavaDoc(stream);
313
314             transformer.transform(source, result);
315             stream.close();
316             return true;
317         } catch (ParserConfigurationException JavaDoc pce) {
318             HelpPlugin.logError(
319                     "DocumentBuilder implementation could not be loaded.", pce); //$NON-NLS-1$
320
return false;
321         } catch (TransformerException JavaDoc e) {
322             HelpPlugin.logError("Problems occurred while saving working sets."); //$NON-NLS-1$
323
return false;
324         } catch (IOException JavaDoc e) {
325             stateFile.delete();
326             HelpPlugin.logError(
327                     "Problems occurred while saving working set file."); //$NON-NLS-1$
328
return false;
329         }
330     }
331
332     /**
333      * Saves all persistable working sets in the persistence store.
334      *
335      * @param parent:
336      * the xml node to save to
337      */

338     private void saveWorkingSetState(Element JavaDoc parent) {
339         Iterator JavaDoc iterator = workingSets.iterator();
340
341         while (iterator.hasNext()) {
342             WorkingSet workingSet = (WorkingSet) iterator.next();
343             workingSet.saveState(parent);
344         }
345     }
346
347     /**
348      * Persists all working sets. Should only be called by the webapp working
349      * set dialog.
350      *
351      * @param changedWorkingSet
352      * the working set that has changed
353      */

354     public void workingSetChanged(WorkingSet changedWorkingSet) {
355         saveState();
356     }
357
358     public AdaptableToc getAdaptableToc(String JavaDoc href) {
359         return getRoot().getAdaptableToc(href);
360     }
361
362     public AdaptableTopic getAdaptableTopic(String JavaDoc id) {
363
364         if (id == null || id.length() == 0)
365             return null;
366
367         // toc id's are hrefs: /pluginId/path/to/toc.xml
368
// topic id's are based on parent toc id and index of topic:
369
// /pluginId/path/to/toc.xml_index_
370
int len = id.length();
371         if (id.charAt(len - 1) == '_') {
372             // This is a first level topic
373
String JavaDoc indexStr = id.substring(id.lastIndexOf('_', len - 2) + 1,
374                     len - 1);
375             int index = 0;
376             try {
377                 index = Integer.parseInt(indexStr);
378             } catch (Exception JavaDoc e) {
379             }
380
381             String JavaDoc tocStr = id.substring(0, id.lastIndexOf('_', len - 2));
382             AdaptableToc toc = getAdaptableToc(tocStr);
383             if (toc == null)
384                 return null;
385             IAdaptable[] topics = toc.getChildren();
386             if (index < 0 || index >= topics.length)
387                 return null;
388             return (AdaptableTopic) topics[index];
389         }
390
391         return null;
392     }
393
394     public String JavaDoc getCurrentWorkingSet() {
395         return HelpBasePlugin.getDefault().getPluginPreferences().getString(
396                 BaseHelpSystem.WORKING_SET);
397     }
398
399     public void setCurrentWorkingSet(String JavaDoc workingSet) {
400         HelpBasePlugin.getDefault().getPluginPreferences().setValue(
401                 BaseHelpSystem.WORKING_SET, workingSet);
402         HelpBasePlugin.getDefault().savePluginPreferences();
403     }
404
405     public void tocsChanged() {
406         saveState();
407         root = null;
408         workingSets = new TreeSet JavaDoc(new WorkingSetComparator());
409         restoreState();
410     }
411
412 }
413
Popular Tags