KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > rice > cs > drjava > model > GlobalModelIOTest


1 /*BEGIN_COPYRIGHT_BLOCK
2  *
3  * This file is part of DrJava. Download the current version of this project from http://www.drjava.org/
4  * or http://sourceforge.net/projects/drjava/
5  *
6  * DrJava Open Source License
7  *
8  * Copyright (C) 2001-2005 JavaPLT group at Rice University (javaplt@rice.edu). All rights reserved.
9  *
10  * Developed by: Java Programming Languages Team, Rice University, http://www.cs.rice.edu/~javaplt/
11  *
12  * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
13  * documentation files (the "Software"), to deal with the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
15  * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
16  *
17  * - Redistributions of source code must retain the above copyright notice, this list of conditions and the
18  * following disclaimers.
19  * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
20  * following disclaimers in the documentation and/or other materials provided with the distribution.
21  * - Neither the names of DrJava, the JavaPLT, Rice University, nor the names of its contributors may be used to
22  * endorse or promote products derived from this Software without specific prior written permission.
23  * - Products derived from this software may not be called "DrJava" nor use the term "DrJava" as part of their
24  * names without prior written permission from the JavaPLT group. For permission, write to javaplt@rice.edu.
25  *
26  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
27  * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28  * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
29  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
30  * WITH THE SOFTWARE.
31  *
32  *END_COPYRIGHT_BLOCK*/

33
34 package edu.rice.cs.drjava.model;
35
36 import java.io.*;
37
38 import java.util.List JavaDoc;
39 import javax.swing.text.BadLocationException JavaDoc;
40
41 import edu.rice.cs.plt.io.IOUtil;
42 import edu.rice.cs.util.FileOpenSelector;
43 import edu.rice.cs.util.Log;
44 import edu.rice.cs.util.OperationCanceledException;
45 import edu.rice.cs.util.UnexpectedException;
46 import edu.rice.cs.util.text.ConsoleDocument;
47 import edu.rice.cs.util.text.EditDocumentException;
48 import edu.rice.cs.util.swing.Utilities;
49 import edu.rice.cs.drjava.model.repl.*;
50 import edu.rice.cs.drjava.DrJava;
51 import edu.rice.cs.drjava.config.OptionConstants;
52
53 /** Test I/O functions of the global model.
54  * @version $Id: GlobalModelIOTest.java 4075 2007-01-19 21:35:50Z dlsmith $
55  */

56 public final class GlobalModelIOTest extends GlobalModelTestCase implements OptionConstants {
57   
58   // _log is inherited from GlobalModelTestCase
59

60   /** Creates a new document, modifies it, and then does the same with a second document, checking for inteference. */
61   public void testMultipleFiles() throws BadLocationException JavaDoc {
62     assertNumOpenDocs(1);
63
64     OpenDefinitionsDocument doc1 = setupDocument(FOO_TEXT);
65     assertNumOpenDocs(2);
66
67     // Create a second, empty document
68
OpenDefinitionsDocument doc2 = _model.newFile();
69     assertNumOpenDocs(3);
70     assertModified(true, doc1);
71     assertModified(false, doc2);
72     assertContents(FOO_TEXT, doc1);
73     assertLength(0, doc2);
74
75     // Modify second document
76
changeDocumentText(BAR_TEXT, doc2);
77     assertModified(true, doc2);
78     assertContents(FOO_TEXT, doc1);
79     assertContents(BAR_TEXT, doc2);
80     
81     _log.log(this + ".testMultipleFiles() completed");
82   }
83
84   /** Opens several documents and ensures that the array returned by the model is correct and in the right order. */
85   public void testMultipleFilesArray() throws BadLocationException JavaDoc {
86     OpenDefinitionsDocument doc1, doc2, doc3;
87     doc1 = setupDocument(FOO_TEXT);
88     doc2 = setupDocument(BAR_TEXT);
89     doc3 = setupDocument(FOO_TEXT);
90     assertNumOpenDocs(4);
91
92     List JavaDoc<OpenDefinitionsDocument> docs = _model.getSortedOpenDefinitionsDocuments();
93     assertEquals("size of document array", 4, docs.size());
94
95     assertEquals("document 1", doc1, docs.get(1));
96     assertEquals("document 2", doc2, docs.get(2));
97     assertEquals("document 3", doc3, docs.get(3));
98     
99     _log.log(this + ".testMultipleFilesArray() completed");
100   }
101
102   /** Ensures closing documents works correctly. */
103   public void testCloseMultipleFiles() throws BadLocationException JavaDoc {
104     assertNumOpenDocs(1);
105     OpenDefinitionsDocument doc1 = setupDocument(FOO_TEXT);
106     assertNumOpenDocs(2);
107     OpenDefinitionsDocument doc2 = setupDocument(BAR_TEXT);
108     assertNumOpenDocs(3);
109
110     _model.closeFile(doc1);
111     assertNumOpenDocs(2);
112
113     List JavaDoc<OpenDefinitionsDocument> docs = _model.getSortedOpenDefinitionsDocuments();
114     assertEquals("size of document array", 2, docs.size());
115     assertContents(BAR_TEXT, docs.get(1));
116
117     _model.closeFile(doc2);
118     assertNumOpenDocs(1);
119     docs = _model.getOpenDefinitionsDocuments();
120     assertEquals("size of document array", 1, docs.size());
121     
122     _log.log(this + ".testCloseMultipleFiles() completed");
123   }
124
125
126   /** Creates a new document, modifies it, then allows it to be closed, ignoring the changes made. */
127   public void testCloseFileAllowAbandon() throws BadLocationException JavaDoc {
128     OpenDefinitionsDocument doc = setupDocument(FOO_TEXT);
129
130     // Try to close and check for proper events
131
TestListener listener = new TestIOListener() {
132       public synchronized boolean canAbandonFile(OpenDefinitionsDocument doc) {
133         canAbandonCount++;
134         return true; // yes allow the abandon
135
}
136     };
137
138     _model.addListener(listener);
139     _model.closeFile(doc);
140     listener.assertAbandonCount(1);
141     listener.assertCloseCount(1); // closed one document
142
listener.assertOpenCount(0);
143     
144     _log.log("testCloseFileAllowAbandon completed");
145   }
146
147   /** Creates a new document, modifies it, but disallows a call to close it without saving changes. */
148   public void testCloseFileDisallowAbandon() throws BadLocationException JavaDoc {
149     OpenDefinitionsDocument doc = setupDocument(FOO_TEXT);
150
151     TestListener listener = new TestIOListener() {
152       public synchronized boolean canAbandonFile(OpenDefinitionsDocument doc) {
153         canAbandonCount++;
154         return false; // no, don't abandon our document!!!
155
}
156     };
157
158     _model.addListener(listener);
159     _model.closeFile(doc);
160     listener.assertAbandonCount(1);
161     listener.assertCloseCount(0);
162     listener.assertOpenCount(0);
163     
164     _log.log("testCloseFileDisallowAbandon completed");
165   }
166
167   /** Opens a file. */
168   public void testOpenRealFile() throws BadLocationException JavaDoc, IOException {
169     final File tempFile = writeToNewTempFile(BAR_TEXT);
170
171     TestListener listener = new TestFileIOListener(tempFile);
172
173     _model.addListener(listener);
174     try {
175       OpenDefinitionsDocument doc = _model.openFile(new FileSelector(tempFile));
176       listener.assertOpenCount(1);
177       listener.assertCloseCount(1); // Untitled document is closed when doc is opened
178
assertModified(false, doc);
179       assertContents(BAR_TEXT, doc);
180     }
181     catch (AlreadyOpenException aoe) {
182       // Should not be open
183
fail("File was already open!");
184     }
185     catch (OperationCanceledException oce) {
186       // Should not be canceled
187
fail("Open was unexpectedly canceled!");
188     }
189     
190     _log.log("testOpenRealFile completed");
191   }
192
193   /** Initiates a file open, but cancels. */
194   public void testCancelOpenFile() throws BadLocationException JavaDoc, IOException {
195
196     OpenDefinitionsDocument doc = setupDocument(FOO_TEXT);
197     assertNumOpenDocs(2);
198
199     TestListener listener = new TestIOListener() {
200       public synchronized boolean canAbandonFile(OpenDefinitionsDocument doc) {
201         canAbandonCount++;
202         return true; // yes allow the abandon
203
}
204     };
205
206     _model.addListener(listener);
207     try {
208       //OpenDefinitionsDocument newDoc =
209
_model.openFile(new CancelingSelector());
210     }
211     catch (AlreadyOpenException aoe) {
212       // Should not be open
213
fail("File was already open!");
214     }
215     catch (OperationCanceledException oce) {
216       // we expect this to be thrown
217
}
218     finally {
219       assertNumOpenDocs(2);
220       listener.assertOpenCount(0);
221       listener.assertCloseCount(0);
222
223       List JavaDoc<OpenDefinitionsDocument> docs = _model.getOpenDefinitionsDocuments();
224       doc = docs.get(1);
225       assertModified(true, doc);
226       assertContents(FOO_TEXT, doc);
227     }
228     
229     _log.log("testCancelOpenFile completed");
230   }
231
232   /** Attempts to open a non-existent file. */
233   public void testOpenNonexistentFile() throws IOException {
234     _model.addListener(new TestListener());
235
236     OpenDefinitionsDocument doc = null;
237
238     try {
239       doc = _model.openFile(new FileSelector(new File("fake-file")));
240       fail("IO exception was not thrown!");
241     }
242     catch (FileNotFoundException fnf) {
243       // As we hoped, the file was not found
244
}
245     catch (AlreadyOpenException aoe) {
246       // Should not be open
247
fail("File was already open!");
248     }
249     catch (OperationCanceledException oce) {
250       // Should not be canceled
251
fail("Open was unexpectedly canceled!");
252     }
253
254     assertEquals("non-existant file", doc, null);
255     
256     _log.log("testOpenNonexistentFile completed");
257   }
258
259   /** Attempts to reopen an already open file. */
260   public void testReopenFile() throws BadLocationException JavaDoc, IOException {
261     final File tempFile = writeToNewTempFile(BAR_TEXT);
262
263     TestListener listener = new TestFileIOListener(tempFile);
264
265     _model.addListener(listener);
266     try {
267       OpenDefinitionsDocument doc = _model.openFile(new FileSelector(tempFile));
268       listener.assertOpenCount(1);
269       listener.assertCloseCount(1); // Untitled document closed when doc is opened
270
assertModified(false, doc);
271       assertContents(BAR_TEXT, doc);
272     }
273     catch (AlreadyOpenException aoe) {
274       // Should not be open
275
fail("File was already open!");
276     }
277     catch (OperationCanceledException oce) {
278       // Should not be canceled
279
fail("Open was unexpectedly canceled!");
280     }
281
282     // Now reopen
283
try {
284       //OpenDefinitionsDocument doc2 =
285
_model.openFile(new FileSelector(tempFile));
286       fail("file should already be open");
287     }
288     catch (AlreadyOpenException aoe) {
289       // Should not be open
290
listener.assertOpenCount(1);
291       listener.assertCloseCount(1);
292     }
293     catch (OperationCanceledException oce) {
294       // Should not be canceled
295
fail("Open was unexpectedly canceled!");
296     }
297
298     // Now reopen same file with a different path
299
// eg. /tmp/MyFile -> /tmp/./MyFile
300
try {
301       File parent = tempFile.getParentFile();
302       String JavaDoc dotSlash = "." + System.getProperty("file.separator");
303       parent = new File(parent, dotSlash);
304       File sameFile = new File(parent, tempFile.getName());
305       //OpenDefinitionsDocument doc2 =
306
_model.openFile(new FileSelector(sameFile));
307       fail("file should already be open");
308     }
309     catch (AlreadyOpenException aoe) {
310       // Should not be open
311
listener.assertOpenCount(1);
312     }
313     catch (OperationCanceledException oce) {
314       // Should not be canceled
315
fail("Open was unexpectedly canceled!");
316     }
317     _log.log("testReopenFile completed");
318   }
319
320   /** Opens multiple files. */
321   public void testOpenMultipleFiles() throws BadLocationException JavaDoc, IOException {
322     final File tempFile1 = writeToNewTempFile(FOO_TEXT);
323     final File tempFile2 = writeToNewTempFile(BAR_TEXT);
324
325     TestListener listener = new TestIOListener() {
326       public void fileOpened(OpenDefinitionsDocument doc) {
327         super.fileOpened(doc);
328         File file = null;
329         try { file = doc.getFile(); }
330         catch (FileMovedException fme) { fail("file does not exist"); } // We know file should exist
331
if (tempFile1.equals(file))
332           assertEquals("file to open", IOUtil.attemptCanonicalFile(tempFile1), IOUtil.attemptCanonicalFile(file));
333         else assertEquals("file to open", IOUtil.attemptCanonicalFile(tempFile2), IOUtil.attemptCanonicalFile(file));
334       }
335     };
336
337     _model.addListener(listener);
338     try {
339       OpenDefinitionsDocument[] docs = _model.openFiles(new FileSelector(tempFile1, tempFile2));
340       listener.assertOpenCount(2);
341       listener.assertCloseCount(1); // closed Untitled document
342
assertEquals("Number of docs returned", docs.length, 2);
343       assertModified(false, docs[0]);
344       assertContents(FOO_TEXT, docs[0]);
345       assertModified(false, docs[1]);
346       assertContents(BAR_TEXT, docs[1]);
347     }
348     catch (AlreadyOpenException aoe) {
349       // Should not be open
350
fail("File was already open!");
351     }
352     catch (OperationCanceledException oce) {
353       // Should not be canceled
354
fail("Open was unexpectedly canceled!");
355     }
356     listener.assertOpenCount(2);
357     List JavaDoc<OpenDefinitionsDocument> docs = _model.getSortedOpenDefinitionsDocuments();
358     assertEquals("size of document array", 2, docs.size());
359     assertContents(FOO_TEXT, docs.get(0));
360     assertContents(BAR_TEXT, docs.get(1));
361     
362     _log.log("testOpenMultipleFiles completed");
363
364   }
365
366   /** Initiates a file open, but cancels. */
367   public void testCancelOpenMultipleFiles() throws BadLocationException JavaDoc, IOException {
368
369     OpenDefinitionsDocument doc1 = setupDocument(FOO_TEXT);
370     OpenDefinitionsDocument doc2 = setupDocument(BAR_TEXT);
371     assertNumOpenDocs(3);
372
373     TestListener listener = new TestIOListener() {
374       public synchronized boolean canAbandonFile(OpenDefinitionsDocument doc) {
375         canAbandonCount++;
376         return true; // yes allow the abandon
377
}
378     };
379
380     _model.addListener(listener);
381     try {
382       //OpenDefinitionsDocument newDoc =
383
_model.openFiles(new CancelingSelector());
384     }
385     catch (AlreadyOpenException aoe) {
386       // Should not be open
387
fail("File was already open!");
388     }
389     catch (OperationCanceledException oce) {
390       // we expect this to be thrown
391
}
392     finally {
393       assertNumOpenDocs(3);
394       listener.assertOpenCount(0);
395       listener.assertCloseCount(0);
396
397       List JavaDoc<OpenDefinitionsDocument> docs = _model.getSortedOpenDefinitionsDocuments();
398       doc1 = docs.get(1);
399       assertModified(true, doc1);
400       assertContents(FOO_TEXT, doc1);
401
402       doc2 = docs.get(2);
403       assertModified(true, doc2);
404       assertContents(BAR_TEXT, doc2);
405     }
406     
407     _log.log("testCancelOpenMultipleFiles completed");
408   }
409
410   /** Attempts to open a non-existent file. */
411   public void testOpenMultipleNonexistentFiles() throws IOException {
412
413     final File tempFile1 = writeToNewTempFile(FOO_TEXT);
414
415     //TestListener listener = new TestListener();
416
TestListener listener = new TestFileIOListener(tempFile1) {
417       public synchronized void fileNotFound(File f) { fileNotFoundCount++; }
418     };
419
420     _model.addListener(listener);
421
422     OpenDefinitionsDocument[] docs = null;
423     try { docs = _model.openFiles(new FileSelector(tempFile1, new File("fake-file"))); }
424     catch (FileNotFoundException fnf) { fail("FileNotFound exception was not thrown!"); } // Should not have moved
425
catch (AlreadyOpenException aoe) { fail("File was already open!"); } // Should not be open
426
catch (OperationCanceledException oce) { fail("Open was unexpectedly canceled!"); } // Should not be canceled
427
assertTrue("one file was opened", docs != null && docs.length == 1);
428     listener.assertOpenCount(1);
429     listener.assertCloseCount(1); // closed Untitled document
430
listener.assertFileNotFoundCount(1);
431     
432     _log.log("testOpenMultipleNonexistentFiles completed");
433   }
434
435   /** Error checking for openening multiple files checks for null and an array w/null. */
436   public void testOpenMultipleFilesError() {
437
438     OpenDefinitionsDocument[] docs = null;
439     //final File tempFile1 = writeToNewTempFile(FOO_TEXT);
440

441     try {
442       docs = _model.openFiles(new FileOpenSelector() {
443         public File[] getFiles() { return new File[] {null}; }
444       });
445       fail("IO exception was not thrown!");
446     }
447     catch (IOException e) { /* As we expected, the file was not found */ }
448     catch (Exception JavaDoc e) { fail("Unexpectedly exception caught!"); }
449
450     try {
451       docs = _model.openFiles(new FileOpenSelector() {
452         public File[] getFiles() { return null; }
453       });
454
455       fail("IO exception was not thrown!");
456     }
457     catch (IOException e) { /* As we expected, the file was not found. */ }
458     catch (Exception JavaDoc e) { fail("Unexpectedly exception caught!"); }
459
460     assertTrue("non-existent file", docs == null);
461     
462     _log.log("testOpenMultipleFilesError completed");
463   }
464
465   /** Force a file to be opened with getDocumentforFile. */
466   public void testForceFileOpen() throws BadLocationException JavaDoc, IOException, OperationCanceledException,
467     AlreadyOpenException {
468     
469     final File tempFile1 = writeToNewTempFile(FOO_TEXT);
470     final File tempFile2 = writeToNewTempFile(BAR_TEXT);
471     // don't catch and fail!
472

473     TestListener listener = new TestIOListener();
474
475     _model.addListener(listener);
476     // Open file 1
477
OpenDefinitionsDocument doc = _model.openFile(new FileSelector(tempFile1));
478     listener.assertOpenCount(1);
479     listener.assertCloseCount(1); // closed Untitled document
480
assertModified(false, doc);
481     assertContents(FOO_TEXT, doc);
482
483     // Get file 1
484
OpenDefinitionsDocument doc1 = _model.getDocumentForFile(tempFile1);
485     listener.assertOpenCount(1);
486     listener.assertCloseCount(1); // closed Untitled document
487
assertEquals("opened document", doc, doc1);
488     assertContents(FOO_TEXT, doc1);
489
490     // Get file 2, forcing it to be opened
491
OpenDefinitionsDocument doc2 = _model.getDocumentForFile(tempFile2);
492     listener.assertOpenCount(2);
493     listener.assertCloseCount(1); // closed Untitled document
494
assertContents(BAR_TEXT, doc2);
495   }
496
497   /** Attempts to make the first save of a document, but cancels instead. */
498   public void testCancelFirstSave() throws BadLocationException JavaDoc, IOException {
499     OpenDefinitionsDocument doc = setupDocument(FOO_TEXT);
500
501     // No need to override methods since no events should be fired
502
_model.addListener(new TestListener());
503
504     boolean saved = doc.saveFile(new CancelingSelector());
505     assertTrue("doc should not have been saved", ! saved);
506     assertModified(true, doc);
507     assertContents(FOO_TEXT, doc);
508     
509     _log.log("testForceFileOpen completed");
510   }
511
512   /** Makes a first save of the current document. */
513   public void testRealSaveFirstSave() throws BadLocationException JavaDoc, IOException {
514     OpenDefinitionsDocument doc = setupDocument(FOO_TEXT);
515     final File file = tempFile();
516
517     TestListener listener = new TestListener() {
518       public void fileSaved(OpenDefinitionsDocument doc) {
519         File f = null;
520         try { f = doc.getFile(); }
521         catch (FileMovedException fme) { fail("file does not exist"); } // We know file should exist
522
try {
523           assertEquals("saved file name", file.getCanonicalFile(), f.getCanonicalFile());
524           synchronized(this) { saveCount++; }
525         }
526         catch (IOException ioe) { fail("could not get canonical file"); }
527       }
528     };
529
530     _model.addListener(listener);
531
532     doc.saveFile(new FileSelector(file));
533     listener.assertSaveCount(1);
534     assertModified(false, doc);
535     assertContents(FOO_TEXT, doc);
536
537     assertEquals("contents of saved file", FOO_TEXT, IOUtil.toString(file));
538     
539     _log.log("testRealSaveFirstSave completed");
540   }
541
542   /** Saves a file already saved and overwrites its contents. */
543   public void testSaveAlreadySaved() throws BadLocationException JavaDoc, IOException {
544     //disable file backups, remember original setting
545
Boolean JavaDoc backupStatus = DrJava.getConfig().getSetting(BACKUP_FILES);
546     DrJava.getConfig().setSetting(BACKUP_FILES, Boolean.FALSE);
547
548     OpenDefinitionsDocument doc = setupDocument(FOO_TEXT);
549     final File file = tempFile();
550
551     // No listeners here -- other tests ensure the first save works
552
doc.saveFile(new FileSelector(file));
553     assertModified(false, doc);
554     assertContents(FOO_TEXT, doc);
555     assertEquals("contents of saved file", FOO_TEXT, IOUtil.toString(file));
556
557     // Listener to use on future saves
558
TestListener listener = new TestListener() {
559       public void fileSaved(OpenDefinitionsDocument doc) {
560         File f = null;
561         try { f = doc.getFile(); }
562         catch (FileMovedException fme) { fail("file does not exist"); } // We know file should exist
563
try {
564           assertEquals("saved file", file.getCanonicalFile(), f.getCanonicalFile());
565           synchronized(this) { saveCount++; }
566         }
567         catch (IOException ioe) { fail("could not get canonical file"); }
568       }
569     };
570
571     File backup = new File(file.getPath() + "~");
572     backup.delete();
573
574     _model.addListener(listener);
575
576     // Muck up the document
577
changeDocumentText(BAR_TEXT, doc);
578
579     // Save over top of the previous file
580
doc.saveFile(new FileSelector(file));
581     
582     Utilities.clearEventQueue();
583     listener.assertSaveCount(1);
584     assertEquals("contents of saved file 2nd write", BAR_TEXT, IOUtil.toString(file));
585     assertFalse("no backup was made", backup.exists());
586
587     //enable file backups
588
DrJava.getConfig().setSetting(BACKUP_FILES, Boolean.TRUE);
589
590     // Muck up the document
591
changeDocumentText(FOO_TEXT, doc);
592     Utilities.clearEventQueue();
593     
594     // Save over top of the previous file
595
doc.saveFile(new FileSelector(file));
596         
597     Utilities.clearEventQueue();
598     listener.assertSaveCount(2);
599     assertEquals("contents of saved file 3rd write", FOO_TEXT, IOUtil.toString(file));
600     assertEquals("contents of backup file 3rd write", BAR_TEXT, IOUtil.toString(backup));
601
602     /* Set the config back to the original option */
603     DrJava.getConfig().setSetting(BACKUP_FILES, backupStatus);
604     
605     _log.log("testSaveAlreadySaved completed");
606   }
607
608   /** Saves the document with FOO_TEXT and then saves over the old text, passing in a CancelingSelector
609    * to cancel if we are asked for a new file name. Confirms that no cancellation happens (since the
610    * file is already saved.
611    */

612   public void testCancelSaveAlreadySaved() throws BadLocationException JavaDoc, IOException {
613     OpenDefinitionsDocument doc = setupDocument(FOO_TEXT);
614     final File file = tempFile();
615
616     // No listeners here -- other tests ensure the first save works
617
doc.saveFile(new FileSelector(file));
618     assertModified(false, doc);
619     assertContents(FOO_TEXT, doc);
620     assertEquals("contents of saved file", FOO_TEXT, IOUtil.toString(file));
621
622     TestListener listener = new TestListener() {
623       public void fileSaved(OpenDefinitionsDocument doc) {
624         File f = null;
625         try { f = doc.getFile(); }
626         catch (FileMovedException fme) { fail("file does not exist"); /* We know file should exist */ }
627         try {
628           assertEquals("saved file", file.getCanonicalFile(), f.getCanonicalFile());
629           synchronized(this) { saveCount++; }
630         }
631         catch (IOException ioe) { fail("could not get canonical file"); }
632       }
633     };
634
635     _model.addListener(listener);
636
637     // Muck up the document
638
changeDocumentText(BAR_TEXT, doc);
639
640     doc.saveFile(new CancelingSelector());
641
642     // The file should have saved on top of the old text anyhow.
643
// The canceling selector should never have been called.
644
listener.assertSaveCount(1);
645     assertModified(false, doc);
646     assertContents(BAR_TEXT, doc);
647
648     assertEquals("contents of saved file", BAR_TEXT, IOUtil.toString(file));
649     
650     _log.log("testCancelSaveAlreadySaved completed");
651   }
652
653   /** Make sure that saveAs doesn't save if we cancel! */
654   public void testCancelSaveAsAlreadySaved() throws BadLocationException JavaDoc, IOException {
655     OpenDefinitionsDocument doc = setupDocument(FOO_TEXT);
656     final File file = tempFile();
657
658     // No listeners here -- other tests ensure the first save works
659
doc.saveFile(new FileSelector(file));
660     assertModified(false, doc);
661     assertContents(FOO_TEXT, doc);
662     assertEquals("contents of saved file", FOO_TEXT, IOUtil.toString(file));
663
664     // No events better be fired!
665
_model.addListener(new TestListener());
666
667     // Muck up the document
668
changeDocumentText(BAR_TEXT, doc);
669
670     doc.saveFileAs(new CancelingSelector());
671
672     assertEquals("contents of saved file", FOO_TEXT, IOUtil.toString(file));
673     
674     _log.log("testCancelSaveAsAlreadySaved completed");
675   }
676
677   /** Ensures that saveAs saves to a different file. */
678   public void testSaveAsAlreadySaved() throws BadLocationException JavaDoc, IOException {
679     OpenDefinitionsDocument doc = setupDocument(FOO_TEXT);
680     final File file1 = tempFile();
681     final File file2 = tempFile();
682
683     // No listeners here -- other tests ensure the first save works
684
doc.saveFile(new FileSelector(file1));
685     assertModified(false, doc);
686     assertContents(FOO_TEXT, doc);
687     assertEquals("contents of saved file", FOO_TEXT, IOUtil.toString(file1));
688
689     // Make sure we save now to the new file name
690
TestListener listener = new TestListener() {
691       public void fileSaved(OpenDefinitionsDocument doc) {
692         File f = null;
693         try { f = doc.getFile(); }
694         catch (FileMovedException fme) { fail("file does not exist"); /* We know file should exist */ }
695         try {
696           assertEquals("saved file", file2.getCanonicalFile(), f.getCanonicalFile());
697           synchronized(this) { saveCount++; }
698         }
699         catch (IOException ioe) { fail("could not get canonical file"); }
700       }
701     };
702
703     _model.addListener(listener);
704
705     // Muck up the document
706
changeDocumentText(BAR_TEXT, doc);
707
708     doc.saveFileAs(new FileSelector(file2));
709
710     assertEquals("contents of saved file1", FOO_TEXT, IOUtil.toString(file1));
711
712     assertEquals("contents of saved file2", BAR_TEXT, IOUtil.toString(file2));
713     
714     _log.log("testSaveAsAlreadySaved completed");
715   }
716
717   public void testSaveAsExistsForOverwrite() throws BadLocationException JavaDoc, IOException {
718
719     OpenDefinitionsDocument doc = setupDocument(FOO_TEXT);
720     final File file1 = tempFile();
721     try {
722       doc.saveFileAs(new WarningFileSelector(file1));
723       fail("Did not ask to verify overwrite as expected");
724     }
725     catch (OverwriteException e1) { /* Good behavior for file saving ... */ }
726     
727     _log.log("testSaveAsExistsForOverwrite completed");
728   }
729
730   public void testSaveAsExistsAndOpen() throws BadLocationException JavaDoc, IOException {
731     OpenDefinitionsDocument doc1,doc2;
732     final File file1,file2;
733
734     file1 = tempFile(1);
735     doc1 = _model.getDocumentForFile(file1);
736     changeDocumentText(FOO_TEXT,doc1);
737     doc1.saveFileAs(new FileSelector(file1));
738
739     file2 = tempFile(2);
740     doc2 = _model.getDocumentForFile(file2);
741     changeDocumentText(BAR_TEXT, doc2);
742
743     try {
744       doc2.saveFileAs(new WarningFileSelector(file1));
745       fail("Did not warn of open file as expected");
746     }
747     catch (OpenWarningException e) { /* Good behavior for file saving ... */ }
748     
749     _log.log("testSaveAsExistsAndOpen completed");
750   }
751
752
753   /** Ensures that all open files are saved in appropriate order, i.e., even with BAR file as active document, save all
754    * should first prompt to save FOO, then BAR.
755    */

756   public void testSaveAllSaveCorrectFiles()
757     throws BadLocationException JavaDoc, IOException {
758     OpenDefinitionsDocument fooDoc = setupDocument(FOO_TEXT);
759     OpenDefinitionsDocument barDoc = setupDocument(BAR_TEXT);
760     OpenDefinitionsDocument trdDoc = setupDocument("third document contents");
761     final File file1 = tempFile();
762     final File file2 = tempFile();
763     final File file3 = tempFile();
764     fooDoc.setFile(file1);
765     barDoc.setFile(file2);
766     trdDoc.setFile(file3);
767     
768     // None of these documents has been entered in the _documentsRepos
769

770     // check.
771
FileSelector fs = new FileSelector(file1);
772
773     _model.saveAllFiles(fs); // this should save the files as file1,file2,file3 respectively
774

775     assertEquals("contents of saved file1", FOO_TEXT, IOUtil.toString(file1));
776     assertEquals("contents of saved file2", BAR_TEXT, IOUtil.toString(file2));
777     assertEquals("contents of saved file3", "third document contents", IOUtil.toString(file3));
778     
779     _log.log("testSaveAllSaveCorrectFiles completed");
780   }
781   
782   /** Forces a file to be opened with getDocumentforFile. */
783   public void testRevertFile() throws BadLocationException JavaDoc, IOException, OperationCanceledException,
784     AlreadyOpenException {
785     
786     final File tempFile1 = writeToNewTempFile(FOO_TEXT);
787     // don't catch and fail!
788

789     TestListener listener = new TestIOListener();
790       
791     _model.addListener(listener);
792     // Open file 1
793
OpenDefinitionsDocument doc = _model.openFile(new FileSelector(tempFile1));
794     listener.assertOpenCount(1);
795     listener.assertCloseCount(1); // closed Untitled document
796
assertModified(false, doc);
797     assertContents(FOO_TEXT, doc);
798
799     assertEquals("original doc unmodified",doc.isModifiedSinceSave(), false);
800     changeDocumentText(BAR_TEXT, doc);
801     assertEquals("doc now modified",doc.isModifiedSinceSave(), true);
802     tempFile1.delete();
803     try {
804       doc.revertFile();
805       fail("File should not be on disk.");
806     }
807     catch (FileMovedException fme) {
808       // Revert should not take place because file is not there.
809
}
810     assertEquals("doc NOT reverted",doc.isModifiedSinceSave(), true);
811     assertContents(BAR_TEXT, doc);
812     
813     _log.log("testRevertFile completed");
814   }
815
816
817   public void testModifiedByOther() throws BadLocationException JavaDoc, IOException, OperationCanceledException,
818     AlreadyOpenException, InterruptedException JavaDoc {
819     
820     final File tempFile1 = writeToNewTempFile(FOO_TEXT);
821     // don't catch and fail!
822

823     TestListener listener = new TestIOListener() {
824       public synchronized void fileReverted(OpenDefinitionsDocument doc) { fileRevertedCount++; }
825       public synchronized boolean shouldRevertFile(OpenDefinitionsDocument doc) {
826         shouldRevertFileCount++;
827         return true;
828       }
829     };
830
831     _model.addListener(listener);
832     // Open file 1
833
OpenDefinitionsDocument doc = _model.openFile(new FileSelector(tempFile1));
834     listener.assertShouldRevertFileCount(0);
835     listener.assertFileRevertedCount(0);
836     assertModified(false, doc);
837
838     doc.revertIfModifiedOnDisk();
839
840     listener.assertShouldRevertFileCount(0);
841     listener.assertFileRevertedCount(0);
842     synchronized(tempFile1) { tempFile1.wait(2000); }
843
844     String JavaDoc s = "THIS IS ONLY A TEST";
845     IOUtil.writeStringToFile(tempFile1, s);
846     assertEquals("contents of saved file", s, IOUtil.toString(tempFile1));
847
848     tempFile1.setLastModified((new java.util.Date JavaDoc()).getTime());
849
850     assertTrue("modified on disk1", doc.modifiedOnDisk());
851     boolean res = doc.revertIfModifiedOnDisk();
852     assertTrue("file reverted", res);
853
854
855     listener.assertShouldRevertFileCount(1);
856     listener.assertFileRevertedCount(1);
857     assertContents(s,doc);
858     
859     _log.log("testModifiedByOther completed");
860   }
861
862   public void testModifiedByOtherFalse() throws BadLocationException JavaDoc, IOException, OperationCanceledException,
863     AlreadyOpenException, InterruptedException JavaDoc {
864     final File tempFile1 = writeToNewTempFile(FOO_TEXT);
865     // don't catch and fail!
866

867     final TestListener listener = new TestIOListener() {
868       public synchronized void fileReverted(OpenDefinitionsDocument doc) { fileRevertedCount++; }
869       public synchronized boolean shouldRevertFile(OpenDefinitionsDocument doc) {
870         shouldRevertFileCount++;
871         return false;
872       }
873     };
874
875     _model.addListener(listener);
876     // Open file 1
877
OpenDefinitionsDocument doc = _model.openFile(new FileSelector(tempFile1));
878     listener.assertShouldRevertFileCount(0);
879     listener.assertFileRevertedCount(0);
880     assertModified(false, doc);
881
882     doc.revertIfModifiedOnDisk();
883     listener.assertShouldRevertFileCount(0);
884     listener.assertFileRevertedCount(0);
885
886     synchronized(tempFile1) { tempFile1.wait(2000); }
887
888     String JavaDoc s = "THIS IS ONLY A TEST";
889     IOUtil.writeStringToFile(tempFile1, s);
890     assertEquals("contents of saved file", s, IOUtil.toString(tempFile1));
891
892     assertTrue("modified on disk1", doc.modifiedOnDisk());
893     boolean reverted = doc.revertIfModifiedOnDisk();
894     assertTrue("modified on disk", reverted == false);
895     listener.assertShouldRevertFileCount(1);
896     listener.assertFileRevertedCount(0);
897     assertContents(FOO_TEXT, doc);
898     
899     
900     _log.log("testModifiedByOtherFalse completed");
901   }
902
903   /** Interprets some statements, saves the history, clears the history, then loads the history. */
904   public void testSaveClearAndLoadHistory() throws EditDocumentException, IOException, InterruptedException JavaDoc {
905     String JavaDoc newLine = System.getProperty("line.separator");
906     InteractionListener listener = new InteractionListener();
907
908     _model.addListener(listener);
909     File f = tempFile();
910     FileSelector fs = new FileSelector(f);
911     String JavaDoc s1 = "int x = 5;";
912     String JavaDoc s2 = "System.out.println(\"x = \" + x)";
913     String JavaDoc s3 = "int y;" + newLine + "int z;";
914     listener.assertInteractionStartCount(0);
915     listener.assertInteractionEndCount(0);
916     
917     interpretIgnoreResult(s1);
918     listener.waitInteractionDone();
919     
920     listener.assertInteractionEndCount(1);
921     listener.assertInteractionStartCount(1);
922     
923     listener.logInteractionStart();
924     interpretIgnoreResult(s2);
925     listener.waitInteractionDone();
926     
927     listener.logInteractionStart();
928     interpretIgnoreResult(s3);
929     listener.waitInteractionDone();
930    
931     // check that the history contains the correct value
932
assertEquals("History and getHistoryAsString should be the same.",
933                  s1 + newLine + s2 + newLine + s3 + newLine,
934                  _model.getHistoryAsString());
935     String JavaDoc delim = History.INTERACTION_SEPARATOR + newLine;
936     assertEquals("History and getHistoryAsStringWithSemicolons don't match up correctly.",
937                  s1 + delim + s2 + delim + s3 + delim,
938                  _model.getHistoryAsStringWithSemicolons());
939     listener.assertInteractionEndCount(3);
940     listener.assertInteractionStartCount(3);
941     _model.saveHistory(fs);
942
943     // check that the file contains the correct value
944
assertEquals("contents of saved file",
945                  History.HISTORY_FORMAT_VERSION_2 +
946                  s1 + delim + s2 + delim + s3 + delim,
947                  IOUtil.toString(f));
948
949     _model.clearHistory();
950     // confirm that the history is clear
951
assertEquals("History is not clear", "", _model.getHistoryAsString());
952     
953     listener.logInteractionStart();
954     _model.loadHistory(fs);
955    listener.waitInteractionDone();
956    
957     // check that output of loaded history is correct
958
ConsoleDocument con = _model.getConsoleDocument();
959     assertEquals("Output of loaded history is not correct",
960                  "x = 5",
961                  con.getDocText(0, con.getLength()).trim());
962     listener.assertInteractionStartCount(4);
963     listener.assertInteractionEndCount(4);
964     _model.removeListener(listener);
965     
966     
967     _log.log("testSaveClearAndLoadHistory completed");
968   }
969
970   /**
971    * Loads two history files, one whose statements end in semicolons, and one whose statements do not.
972    * Makes sure that it doesn't matter.
973    */

974   public void testLoadHistoryWithAndWithoutSemicolons() throws IOException, EditDocumentException,
975     InterruptedException JavaDoc {
976     
977     InteractionListener listener = new InteractionListener();
978     _model.addListener(listener);
979     File f1 = tempFile(1);
980     File f2 = tempFile(2);
981     FileSelector fs1 = new FileSelector(f1);
982     FileSelector fs2 = new FileSelector(f2);
983     String JavaDoc s1 = "int x = 5;";
984     String JavaDoc s2 = "System.out.println(\"x = \" + x)";
985     String JavaDoc s3 = "x = 5;";
986     String JavaDoc s4 = "System.out.println(\"x = \" + x)";
987     IOUtil.writeStringToFile(f1,s1+'\n'+s2+'\n');
988     IOUtil.writeStringToFile(f2,s3+'\n'+s4+'\n');
989
990     listener.assertInteractionStartCount(0);
991     _model.loadHistory(fs1);
992     listener.waitInteractionDone();
993
994     listener.logInteractionStart();
995     _model.loadHistory(fs2);
996     listener.waitInteractionDone();
997     
998     // check that output of loaded history is correct
999
ConsoleDocument con = _model.getConsoleDocument();
1000    assertEquals("Output of loaded history is not correct: " + con.getDocText(0, con.getLength()).trim(),
1001                 "x = 5" + System.getProperty("line.separator") + "x = 5",
1002                 con.getDocText(0, con.getLength()).trim());
1003    
1004    
1005    _log.log("testLoadHistoryWithAndWithoutSemicolons completed");
1006  }
1007
1008  /** Test for the possibility that the file has been moved or deleted
1009   * since it was last referenced
1010   */

1011  public void testFileMovedWhenTriedToSave()
1012    throws BadLocationException JavaDoc, IOException {
1013
1014    OpenDefinitionsDocument doc = setupDocument(FOO_TEXT);
1015    final File file = tempFile();
1016
1017    doc.saveFile(new FileSelector(file));
1018
1019    TestListener listener = new TestListener();
1020
1021    _model.addListener(listener);
1022
1023    file.delete();
1024    changeDocumentText(BAR_TEXT, doc);
1025    try {
1026      doc.saveFile(new WarningFileSelector(file));
1027      fail("Save file should have thrown an exception");
1028    }
1029    catch (GlobalModelTestCase.FileMovedWarningException fme) {
1030      // this is expected to occur:
1031
// WarningFileSelector throws it in shouldSaveAfterFileMoved()
1032
}
1033
1034    assertModified(true, doc);
1035    assertContents(BAR_TEXT, doc);
1036    
1037    
1038    _log.log("testFileMovedWhenTriedToSave completed");
1039  }
1040
1041  /** Tests that input can be written to and read from the console correctly. */
1042  public void testConsoleInput() throws EditDocumentException {
1043    _model.getInteractionsModel().setInputListener(new InputListener() {
1044      int n = 0;
1045      public String JavaDoc getConsoleInput() {
1046        n++;
1047        if (n > 1) throw new IllegalStateException JavaDoc("Input should only be requested once!");
1048        return "input\n";
1049      }
1050    });
1051
1052    String JavaDoc result = interpret("System.in.read()");
1053    String JavaDoc expected = /* DefaultInteractionsModel.INPUT_REQUIRED_MESSAGE + */ String.valueOf((int)'i');
1054    assertEquals("read() should prompt for input and return the first byte of \"input\"", expected, result);
1055
1056    interpret("import java.io.*;");
1057    interpret("br = new BufferedReader(new InputStreamReader(System.in))");
1058    result = interpret("br.readLine()");
1059    assertEquals("readLine() should return the rest of \"input\" without prompting for input",
1060                 "\"nput\"", result);
1061    
1062    
1063    _log.log("testConsoleInput completed");
1064  }
1065  
1066  class TestIOListener extends TestListener {
1067    public synchronized void fileOpened(OpenDefinitionsDocument doc) { openCount++; }
1068    public synchronized void fileClosed(OpenDefinitionsDocument doc) { closeCount++; }
1069  }
1070  
1071  class TestFileIOListener extends TestIOListener {
1072    File _expected;
1073    TestFileIOListener(File f) { _expected = f; }
1074    public void fileOpened(OpenDefinitionsDocument doc) {
1075      super.fileOpened(doc);
1076      File file = null;
1077      try { file = doc.getFile(); }
1078      catch (FileMovedException fme) { fail("file does not exist"); } // We know file should exist
1079
assertEquals("file to open", IOUtil.attemptCanonicalFile(_expected), IOUtil.attemptCanonicalFile(file));
1080    }
1081  }
1082}
1083
Popular Tags