KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > armedbear > j > Session


1 /*
2  * Session.java
3  *
4  * Copyright (C) 1998-2003 Peter Graves
5  * $Id: Session.java,v 1.11 2003/06/29 00:19:34 piso Exp $
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20  */

21
22 package org.armedbear.j;
23
24 import java.io.BufferedWriter JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.OutputStreamWriter JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.List JavaDoc;
31 import org.xml.sax.Attributes JavaDoc;
32 import org.xml.sax.InputSource JavaDoc;
33 import org.xml.sax.SAXException JavaDoc;
34 import org.xml.sax.XMLReader JavaDoc;
35 import org.xml.sax.helpers.DefaultHandler JavaDoc;
36 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
37
38 public final class Session extends DefaultHandler JavaDoc implements Constants
39 {
40     private static File sessionDirectory;
41
42     private final File file;
43
44     private List JavaDoc bufferEntries;
45     private SessionBufferEntry currentBufferEntry;
46
47     private Session()
48     {
49         file = File.getInstance(Directories.getEditorDirectory(), "session.xml");
50     }
51
52     private Session(File file)
53     {
54         this.file = file;
55     }
56
57     public static File getSessionDirectory()
58     {
59         if (sessionDirectory == null) {
60             sessionDirectory =
61                 File.getInstance(Directories.getEditorDirectory(), "sessions");
62             if (!sessionDirectory.isDirectory()) {
63                 sessionDirectory.mkdirs();
64                 if (!sessionDirectory.isDirectory())
65                     Log.error("unable to create session directory!");
66             }
67         }
68         return sessionDirectory;
69     }
70
71     private static File getSessionFile(String JavaDoc name)
72     {
73         return File.getInstance(getSessionDirectory(), name);
74     }
75
76     public static Session getSession(String JavaDoc name)
77     {
78         File file = getSessionFile(name);
79         if (file != null && file.isFile())
80             return new Session(file);
81         return null;
82     }
83
84     public static Session getDefaultSession()
85     {
86         return new Session();
87     }
88
89     public static void saveDefaultSession()
90     {
91         getDefaultSession().save();
92     }
93
94     public static void saveCurrentSession()
95     {
96         String JavaDoc name = Editor.getSessionName();
97         if (name != null) {
98             File file = getSessionFile(name);
99             if (file != null) {
100                 Session session = new Session(file);
101                 session.save();
102             }
103         }
104     }
105
106     public static void saveSession()
107     {
108         String JavaDoc name = Editor.getSessionName();
109         if (name == null) {
110             ChooseSessionDialog d = new ChooseSessionDialog("Save Session");
111             d.show();
112             name = d.getInput();
113         }
114         if (name != null)
115             saveSession(name);
116     }
117
118     public static void saveSession(String JavaDoc name)
119     {
120         File file = getSessionFile(name);
121         if (file != null) {
122             Session session = new Session(file);
123             session.save();
124             Editor.setSessionName(name);
125             Editor.currentEditor().status("Session saved");
126         }
127     }
128
129     public static void loadSession()
130     {
131         ChooseSessionDialog d = new ChooseSessionDialog("Load Session");
132         d.show();
133         String JavaDoc name = d.getInput();
134         if (name != null)
135             loadSession(name);
136     }
137
138     public static void loadSession(String JavaDoc name)
139     {
140         File file = getSessionFile(name);
141         if (file == null)
142             return;
143         if (!file.isFile()) {
144             String JavaDoc message = "File \"" + file.canonicalPath() + "\" not found";
145             MessageDialog.showMessageDialog(message, "Load Session");
146             return;
147         }
148         final Editor editor = Editor.currentEditor();
149         for (BufferIterator it = new BufferIterator(); it.hasNext();) {
150             if (!editor.okToClose(it.nextBuffer()))
151                 return;
152         }
153         // Load new session.
154
Session session = new Session(file);
155         if (!session.load()) {
156             Log.error("unable to load session from " + file);
157             MessageDialog.showMessageDialog(
158                 "Unable to load session from " + file,
159                 "Load Session");
160             return;
161         }
162
163         if (Editor.getSessionName() != null)
164             if (Editor.preferences().getBooleanProperty(Property.AUTOSAVE_NAMED_SESSIONS))
165                 saveCurrentSession();
166
167         Marker.invalidateAllMarkers();
168
169         editor.setWaitCursor();
170         // Close all the existing buffers.
171
for (BufferIterator iter = new BufferIterator(); iter.hasNext();) {
172             Buffer buf = iter.nextBuffer();
173             for (EditorIterator it = new EditorIterator(); it.hasNext();) {
174                 Editor ed = it.nextEditor();
175                 ed.views.remove(buf);
176             }
177             buf.deleteAutosaveFile();
178             iter.remove();
179             buf.dispose();
180         }
181         editor.unsplitWindow();
182         Buffer toBeActivated = session.createBuffers();
183         // Make sure read-only status is correct for each buffer.
184
for (BufferIterator it = new BufferIterator(); it.hasNext();)
185             editor.reactivate(it.nextBuffer());
186         for (EditorIterator it = new EditorIterator(); it.hasNext();)
187             it.nextEditor().activate(toBeActivated);
188         Sidebar.setUpdateFlagInAllFrames(SIDEBAR_BUFFER_LIST_CHANGED);
189         Sidebar.refreshSidebarInAllFrames();
190         Editor.setSessionName(name);
191         editor.setDefaultCursor();
192     }
193
194     public Buffer restore()
195     {
196         if (file == null) {
197             Debug.bug();
198             return null;
199         }
200         if (!file.isFile())
201             return null;
202         if (!load()) {
203             Log.error("Session.restore unable to load " + file);
204             return null;
205         }
206         return createBuffers();
207     }
208
209     private Buffer createBuffers()
210     {
211         long start = System.currentTimeMillis();
212         Buffer toBeActivated = null;
213         long lastActivated = 0;
214         Iterator JavaDoc iter = bufferEntries.iterator();
215         while (iter.hasNext()) {
216             SessionBufferEntry entry = (SessionBufferEntry) iter.next();
217             if (entry != null) {
218                 File file = File.getInstance(entry.getPath());
219                 if (file != null && file.isLocal()) {
220                     Buffer buf = null;
221                     if (file.isDirectory())
222                         buf = new Directory(file);
223                     else if (file.isFile() && file.canRead()) {
224                         if (entry.getModeId() == WEB_MODE)
225                             buf = WebBuffer.createWebBuffer(file, null, null);
226                         else
227                             buf = Buffer.precreateBuffer(file);
228                     }
229                     if (buf != null) {
230                         buf.setLastView(new View(entry));
231                         if (toBeActivated == null ||
232                             entry.getLastActivated() > lastActivated) {
233                             toBeActivated = buf;
234                             lastActivated = entry.getLastActivated();
235                         }
236                     }
237                 } else {
238                     Log.error("Session.createBuffers file = " + file);
239                     Debug.bug();
240                 }
241             }
242         }
243         if (toBeActivated == null)
244             toBeActivated = Editor.getBufferList().getFirstBuffer();
245         long elapsed = System.currentTimeMillis() - start;
246         Log.debug("createBuffers " + Editor.getBufferList().size() +
247             " buffers " + elapsed + " ms");
248         return toBeActivated;
249     }
250
251     public void save()
252     {
253         try {
254             File tempFile = Utilities.getTempFile();
255             BufferedWriter JavaDoc writer =
256                 new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(
257                     tempFile.getOutputStream()));
258             writer.write("<?xml version=\"1.0\"?>");
259             writer.newLine();
260             writer.write("<session version=\"" + getVersion() + "\">");
261             writer.newLine();
262             writer.write(" <buffers>");
263             writer.newLine();
264             int index = 0;
265             for (BufferIterator it = new BufferIterator(); it.hasNext();) {
266                 Buffer buf = it.nextBuffer();
267                 // Skip shell, compilation, HTTP buffers etc.
268
if (!buf.canBeRestored())
269                     continue;
270                 // Skip untitled buffers.
271
if (buf.getFile() == null)
272                     continue;
273                 SessionBufferEntry entry = new SessionBufferEntry(buf, index++);
274                 writer.write(entry.toXml());
275                 writer.newLine();
276             }
277             writer.write(" </buffers>");
278             writer.newLine();
279             writer.write("</session>");
280             writer.newLine();
281             writer.flush();
282             writer.close();
283             Utilities.deleteRename(tempFile, file);
284         }
285         catch (IOException JavaDoc e) {
286             Log.error(e);
287         }
288     }
289
290     private boolean load()
291     {
292         InputStream JavaDoc inputStream = null;
293         try {
294             if (file != null && file.isFile())
295                 inputStream = file.getInputStream();
296         }
297         catch (IOException JavaDoc e) {
298             Log.error(e);
299             return false;
300         }
301         if (inputStream == null)
302             return false;
303         XMLReader JavaDoc xmlReader = Utilities.getDefaultXMLReader();
304         if (xmlReader == null)
305             return false;
306         xmlReader.setContentHandler(this);
307         try {
308             InputSource JavaDoc inputSource = new InputSource JavaDoc(inputStream);
309             xmlReader.parse(inputSource);
310         }
311         catch (Exception JavaDoc e) {
312             Log.error(e);
313             return false;
314         }
315         if (bufferEntries == null)
316             return false;
317         // Make sure we can open at least one buffer.
318
Iterator JavaDoc iter = bufferEntries.iterator();
319         while (iter.hasNext()) {
320             SessionBufferEntry entry = (SessionBufferEntry) iter.next();
321             if (entry != null) {
322                 File file = File.getInstance(entry.getPath());
323                 Debug.assertTrue(file.isLocal());
324                 if (file.exists())
325                     return true;
326             }
327         }
328         return false;
329     }
330
331     public void startElement(String JavaDoc uri, String JavaDoc localName, String JavaDoc qName,
332         Attributes JavaDoc attributes) throws SAXException JavaDoc
333     {
334         if (localName.equals("buffer") || qName.equals("buffer")) {
335             currentBufferEntry = new SessionBufferEntry();
336             String JavaDoc path = attributes.getValue("", "path");
337             currentBufferEntry.setPath(path);
338             String JavaDoc mode = attributes.getValue("", "mode");
339             currentBufferEntry.setMode(mode);
340             String JavaDoc dot = attributes.getValue("", "dot");
341             int index = dot.indexOf(',');
342             if (index >= 0) {
343                 String JavaDoc s1 = dot.substring(0, index);
344                 String JavaDoc s2 = dot.substring(index + 1);
345                 try {
346                     currentBufferEntry.setDotLineNumber(Integer.parseInt(s1));
347                     currentBufferEntry.setDotOffset(Integer.parseInt(s2));
348                 }
349                 catch (NumberFormatException JavaDoc e) {
350                     Log.error(e);
351                 }
352             }
353             String JavaDoc when = attributes.getValue("", "when");
354             try {
355                 currentBufferEntry.setLastActivated(Long.parseLong(when));
356             }
357             catch (NumberFormatException JavaDoc e) {
358                 Log.error(e);
359             }
360         }
361     }
362
363     public void endElement(String JavaDoc uri, String JavaDoc localName, String JavaDoc qName)
364     {
365         if (localName.equals("buffer") || qName.equals("buffer")) {
366             if (bufferEntries == null)
367                 bufferEntries = new ArrayList JavaDoc();
368             bufferEntries.add(currentBufferEntry);
369         }
370     }
371
372     private final int getVersion()
373     {
374         return 1;
375     }
376 }
377
Popular Tags