source: trunk/src/org/expeditee/gui/FrameIO.java@ 282

Last change on this file since 282 was 282, checked in by ra33, 16 years ago
File size: 35.9 KB
Line 
1package org.expeditee.gui;
2
3import java.io.BufferedReader;
4import java.io.BufferedWriter;
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.FileNotFoundException;
8import java.io.FileOutputStream;
9import java.io.FileReader;
10import java.io.FileWriter;
11import java.io.IOException;
12import java.sql.Time;
13import java.util.Collection;
14import java.util.HashMap;
15import java.util.LinkedList;
16
17import org.expeditee.agents.ExistingFramesetException;
18import org.expeditee.io.Conversion;
19import org.expeditee.io.ExpReader;
20import org.expeditee.io.ExpWriter;
21import org.expeditee.io.FrameReader;
22import org.expeditee.io.FrameWriter;
23import org.expeditee.io.KMSReader;
24import org.expeditee.io.KMSWriter;
25import org.expeditee.io.Logger;
26import org.expeditee.items.Item;
27import org.expeditee.items.ItemUtils;
28import org.expeditee.items.Permission;
29import org.expeditee.items.Text;
30import org.expeditee.stats.SessionStats;
31
32/**
33 * This class provides static methods for all saving and loading of Frames
34 * to\from disk. This class also handles any caching of previously loaded
35 * Frames.
36 *
37 * @author jdm18
38 *
39 */
40public class FrameIO {
41
42 private static final char FRAME_NAME_LAST_CHAR = 'A';
43
44 public static void changeParentFolder(String newFolder) {
45 PARENT_FOLDER = newFolder;
46 FRAME_PATH = PARENT_FOLDER + "framesets" + File.separator;
47 TRASH_PATH = PARENT_FOLDER + "trash" + File.separator;
48 IMAGES_PATH = PARENT_FOLDER + IMAGES_FOLDER;
49 HELP_PATH = PARENT_FOLDER + "documentation" + File.separator;
50 PROFILE_PATH = PARENT_FOLDER + "profiles" + File.separator;
51 EXPORTS_DIR = PARENT_FOLDER + "exports" + File.separator;
52 STATISTICS_DIR = PARENT_FOLDER + "statistics" + File.separator;
53 LOGS_DIR = PARENT_FOLDER + "logs" + File.separator;
54 }
55
56 /**
57 * The default location for storing the framesets. Each frameset has its own
58 * subdirectory in this directory.
59 */
60 public static String IMAGES_FOLDER = "images" + File.separator;
61
62 public static String TRASH_PATH;
63
64 public static String PARENT_FOLDER;
65
66 public static String FRAME_PATH;
67
68 public static String IMAGES_PATH;
69
70 public static String HELP_PATH;
71
72 public static String PROFILE_PATH;
73
74 public static String EXPORTS_DIR;
75
76 public static String STATISTICS_DIR;
77
78 public static String LOGS_DIR;
79
80 private static final String INF_FILENAME = "frame.inf";
81
82 public static final String ILLEGAL_CHARS = ";:\\/?";
83
84 public static final int MAX_NAME_LENGTH = 64;
85
86 public static final int MAX_CACHE = 100;
87
88 private static HashMap<String, Frame> _Cache = new FrameCache();
89
90 // private static HashMap<String, String> _FramesetNameCache = new
91 // HashMap<String, String>();
92
93 private static boolean ENABLE_CACHE = true;
94
95 private static boolean _UseCache = true;
96
97 private static boolean _SuspendedCache = false;
98
99 // All methods are static, this should not be instantiated
100 private FrameIO() {
101 }
102
103 public static boolean isCacheOn() {
104 return _UseCache && ENABLE_CACHE;
105 }
106
107 public static void Precache(String framename) {
108 // if the cache is turned off, do nothing
109 if (!isCacheOn())
110 return;
111
112 // if the frame is already in the cache, do nothing
113 if (_Cache.containsKey(framename.toLowerCase()))
114 return;
115
116 // otherwise, load the frame and put it in the cache
117 Logger.Log(Logger.SYSTEM, Logger.LOAD, "Precaching " + framename + ".");
118
119 // do not display errors encountered to the user
120 // (they will be shown at load time)
121 MessageBay.supressMessages(true);
122 // loading automatically caches the frame is caching is turned on
123 LoadUnknownPath(framename, false);
124 MessageBay.supressMessages(false);
125 }
126
127 /**
128 * Checks if a string is a representation of a positive integer.
129 *
130 * @param s
131 * @return true if s is a positive integer
132 */
133 public static boolean isPositiveInteger(String s) {
134 if (s == null || s.length() == 0)
135 return false;
136
137 for (int i = 0; i < s.length(); i++) {
138 if (!Character.isDigit(s.charAt(i)))
139 return false;
140 }
141 return true;
142 }
143
144 public static Frame LoadFrame(String frameName) {
145 return LoadFrame(frameName, false);
146 }
147
148 public static Frame LoadFrame(String frameName, boolean ignoreAnnotations) {
149 if (!isValidFrameName(frameName))
150 return null;
151
152 String frameNameLower = frameName.toLowerCase();
153 // first try reading from cache
154 if (isCacheOn() && _Cache.containsKey(frameNameLower)) {
155 Logger.Log(Logger.SYSTEM, Logger.LOAD, "Loading " + frameName
156 + " from cache.");
157 Frame frame = _Cache.get(frameNameLower);
158 return frame;
159 }
160
161 Logger.Log(Logger.SYSTEM, Logger.LOAD, "Loading " + frameName
162 + " from disk.");
163 return LoadUnknownPath(frameName, ignoreAnnotations);
164 }
165
166 private static Frame LoadUnknownPath(String framename, boolean ignoreAnnotations) {
167 Frame loaded = null;
168
169 for (String path : UserSettings.FrameDirs) {
170 loaded = LoadFrame(path, framename);
171 if (loaded != null) {
172 FrameUtils.Parse(loaded, true, ignoreAnnotations);
173 break;
174 }
175 }
176
177 return loaded;
178 }
179
180 /**
181 * Gets a list of all the framesets available to the user
182 *
183 * @return a string containing a list of all the available framesets on
184 * separate lines
185 */
186 public static String getFramesetList() {
187 StringBuffer list = new StringBuffer();
188
189 for (String path : UserSettings.FrameDirs) {
190 File files = new File(path);
191 if (!files.exists())
192 continue;
193 for (File f : (new File(path)).listFiles()) {
194 if (f.isDirectory()) {
195 list.append(f.getName()).append('\n');
196 }
197 }
198 }
199 // remove the final new line char
200 list.deleteCharAt(list.length() - 1);
201 return list.toString();
202 }
203
204 /**
205 * Gets the full path and file name of the frame.
206 *
207 * @param path-
208 * the directory in which to look for the frameset containing the
209 * frame.
210 * @param frameName-
211 * the name of the frame for which the path is being requested.
212 * @return null if the frame can not be located.
213 */
214 public static synchronized String getFrameFullPathName(String path, String frameName) {
215 String source = path + Conversion.getFramesetName(frameName)
216 + File.separator;
217
218 File tester = new File(source);
219 if (!tester.exists())
220 return null;
221
222 // check for the new file name format
223 String fullPath = source + Conversion.getFrameNumber(frameName)
224 + ExpReader.EXTENTION;
225 tester = new File(fullPath);
226
227 if (tester.exists())
228 return fullPath;
229
230 // check for oldfile name format
231 fullPath = source + Conversion.getFramesetName(frameName) + "."
232 + Conversion.getFrameNumber(frameName);
233 tester = new File(fullPath);
234
235 if (tester.exists())
236 return fullPath;
237
238 return null;
239 }
240
241 public static boolean canAccessFrame(String frameName) {
242 for (String path : UserSettings.FrameDirs) {
243 if (getFrameFullPathName(path, frameName) != null)
244 return true;
245 }
246 return false;
247 }
248
249 public static Collection<String> searchFrame(String frameName,
250 String pattern, String path) {
251 String fullPath = null;
252 if (path == null) {
253 for (String possiblePath : UserSettings.FrameDirs) {
254 fullPath = getFrameFullPathName(possiblePath, frameName);
255 if (fullPath != null)
256 break;
257 }
258 } else {
259 fullPath = getFrameFullPathName(path, frameName);
260 }
261 // If the frame was not located return null
262 if (fullPath == null)
263 return null;
264 Collection<String> results = new LinkedList<String>();
265 // Open the file and search the text items
266 try {
267 BufferedReader reader = new BufferedReader(new FileReader(fullPath));
268 String next;
269 while (reader.ready() && ((next = reader.readLine()) != null)) {
270 if (next.startsWith("T")) {
271 String toSearch = next.substring(2);
272 if (toSearch.toLowerCase().contains(pattern))
273 results.add(toSearch);
274 }
275 }
276 } catch (FileNotFoundException e) {
277 e.printStackTrace();
278 return null;
279 } catch (IOException e) {
280 e.printStackTrace();
281 }
282 return results;
283 }
284
285 private static Frame LoadFrame(String path, String frameName) {
286 String fullPath = getFrameFullPathName(path, frameName);
287 if (fullPath == null)
288 return null;
289
290 try {
291 FrameReader reader;
292
293 if (fullPath.endsWith(ExpReader.EXTENTION)) {
294 reader = new ExpReader(frameName);
295 } else {
296 reader = new KMSReader();
297 }
298 Frame frame = reader.readFrame(fullPath);
299
300 if (frame == null) {
301 MessageBay.errorMessage("Error: " + frameName
302 + " could not be successfully loaded.");
303 return null;
304 }
305
306 frame.path = path;
307
308 // do not put 0 frames or virtual frames into the cache
309 if (_Cache.size() > MAX_CACHE)
310 _Cache.clear();
311
312 if (frame.getNumber() > 0 && isCacheOn())
313 _Cache.put(frameName.toLowerCase(), frame);
314
315 return frame;
316 } catch (IOException ioe) {
317 ioe.printStackTrace();
318 Logger.Log(ioe);
319 } catch (Exception e) {
320 e.printStackTrace();
321 Logger.Log(e);
322 MessageBay.errorMessage("Error: " + frameName
323 + " could not be successfully loaded.");
324 }
325
326 return null;
327 }
328
329 public static void Reload() {
330 // disable cache
331 boolean cache = _UseCache;
332
333 _UseCache = false;
334 Frame fresh = FrameIO.LoadFrame(DisplayIO.getCurrentFrame().getName());
335 _UseCache = cache;
336 if (_Cache.containsKey(fresh.getName().toLowerCase()))
337 addToCache(fresh);
338 DisplayIO.setCurrentFrame(fresh, false);
339 }
340
341 public static Frame LoadPrevious(Frame current) {
342 checkTDFC(current);
343
344 // the current name and number
345 String name = current.getFramesetName();
346 int num = current.getNumber() - 1;
347
348 // loop until a frame that exists is found
349 for (; num >= 0; num--) {
350 Frame f = LoadFrame(name + num);
351 if (f != null)
352 return f;
353 }
354
355 // if we did not find another Frame then this one must be the last one
356 // in the frameset
357 MessageBay
358 .displayMessageOnce("This is the first frame in the frameset");
359 return null;
360 }
361
362 /**
363 * Returns the next Frame in the current Frameset (The Frame with the next
364 * highest Frame number) If the current Frame is the last one in the
365 * Frameset, or an error occurs then null is returned.
366 *
367 * @return The Frame after this one in the current frameset, or null
368 */
369 public static Frame LoadNext(Frame current) {
370 checkTDFC(current);
371
372 // the current name and number
373 int num = current.getNumber() + 1;
374 int max = num + 1;
375 String name = current.getFramesetName();
376
377 // read the maximum from the INF file
378 try {
379 max = ReadINF(current.path, current.getFramesetName());
380 } catch (IOException ioe) {
381 MessageBay.errorMessage("Error loading INF file for frameset '"
382 + name + "'");
383 return null;
384 }
385
386 // loop until a frame that exists is found
387 for (; num <= max; num++) {
388 Frame f = LoadFrame(name + num);
389 if (f != null)
390 return f;
391 }
392
393 // if we did not find another Frame then this one must be the last one
394 // in the frameset
395 MessageBay.displayMessageOnce("This is the last frame in the frameset");
396 return null;
397 }
398
399 /**
400 * This method checks if the current frame has just been created with TDFC.
401 * If it has the frame is saved regardless of whether it has been edited or
402 * not and the TDFC item property is cleared. This is to ensure that the
403 * link is saved on the parent frame.
404 *
405 * @param current
406 */
407 public static void checkTDFC(Frame current) {
408 if (FrameUtils.getTdfcItem() != null) {
409 FrameUtils.setTdfcItem(null);
410 current.change();
411 }
412 }
413
414 public static Frame LoadLast(String framesetName, String path) {
415 // read the maximum from the INF file
416 int max;
417 try {
418 max = ReadINF(path, framesetName);
419 } catch (IOException ioe) {
420 MessageBay.errorMessage("Error loading INF file for frameset '"
421 + framesetName + "'");
422 return null;
423 }
424
425 // loop backwards until a frame that exists is found
426 for (int num = max; num > 0; num--) {
427 Frame f = LoadFrame(framesetName + num);
428 if (f != null)
429 return f;
430 }
431
432 // if we did not find another Frame then this one must be the last one
433 // in the frameset
434 MessageBay.displayMessage("This is the last frame in the frameset");
435 return null;
436 }
437
438 public static Frame LoadZero(String framesetName, String path) {
439 return LoadFrame(framesetName + 0);
440 }
441
442 public static Frame LoadZero() {
443 Frame current = DisplayIO.getCurrentFrame();
444 return LoadZero(current.getFramesetName(), current.path);
445 }
446
447 public static Frame LoadLast() {
448 Frame current = DisplayIO.getCurrentFrame();
449 return LoadLast(current.getFramesetName(), current.path);
450 }
451
452 public static Frame LoadNext() {
453 return LoadNext(DisplayIO.getCurrentFrame());
454 }
455
456 public static Frame LoadPrevious() {
457 return LoadPrevious(DisplayIO.getCurrentFrame());
458 }
459
460 /**
461 * Deletes the given Frame on disk and removes the cached Frame if there is
462 * one. Also adds the deleted frame into the deletedFrames frameset.
463 *
464 * @param toDelete
465 * The Frame to be deleted
466 * @return The name the deleted frame was changed to, or null if the delete
467 * failed
468 */
469 public static String DeleteFrame(Frame toDelete) throws IOException,
470 SecurityException {
471 if (toDelete == null)
472 return null;
473
474 // Dont delete the zero frame
475 if (toDelete.getNumber() == 0) {
476 throw new SecurityException("Deleting a zero frame is illegal");
477 }
478
479 SaveFrame(toDelete);
480
481 // Copy deleted frames to the DeletedFrames frameset
482 // get the last used frame in the destination frameset
483 final String DELETED_FRAMES = "DeletedFrames";
484 int lastNumber = FrameIO.getLastNumber(DELETED_FRAMES);
485 String framePath;
486 try {
487 // create the new frameset
488 Frame one = FrameIO.CreateFrameset(DELETED_FRAMES, toDelete.path);
489 framePath = one.path;
490 lastNumber = 0;
491 } catch (Exception e) {
492 Frame zero = FrameIO.LoadFrame(DELETED_FRAMES + "0");
493 framePath = zero.path;
494 }
495
496 // get the fill path to determine which file version it is
497 String source = getFrameFullPathName(toDelete.path, toDelete.getName());
498
499 String oldFrameName = toDelete.getName().toLowerCase();
500 // Now save the frame in the new location
501 toDelete.setFrameset(DELETED_FRAMES);
502 toDelete.setFrameNumber(lastNumber + 1);
503 toDelete.path = framePath;
504 ForceSaveFrame(toDelete);
505
506 if (_Cache.containsKey(oldFrameName))
507 _Cache.remove(oldFrameName);
508
509 File del = new File(source);
510
511 java.io.FileInputStream ff = new java.io.FileInputStream(del);
512 ff.close();
513
514 if (del.delete()) {
515 return toDelete.getName();
516 }
517
518 return null;
519 }
520
521 /**
522 * Creates a new Frame in the given frameset and assigns it the given Title,
523 * which can be null. The newly created Frame is a copy of the frameset's .0
524 * file with the number updated based on the last recorded Frame name in the
525 * frameset's INF file.
526 *
527 * @param frameset
528 * The frameset to create the new Frame in
529 * @param frameTitle
530 * The title to assign to the newly created Frame (can be NULL).
531 * @return The newly created Frame.
532 */
533 public static synchronized Frame CreateFrame(String frameset, String frameTitle,
534 String templateFrame) throws RuntimeException {
535
536 if (!FrameIO.isValidFramesetName(frameset)) {
537 throw new RuntimeException(frameset
538 + " is not a valid frameset name");
539 }
540
541 int next = -1;
542
543 // disable caching of 0 frames
544 SuspendCache();
545 String zeroFrameName = frameset + "0";
546 Frame destFramesetZero = LoadFrame(zeroFrameName);
547 if (destFramesetZero == null) {
548 throw new RuntimeException(zeroFrameName + " could not be found");
549 }
550
551 Frame template = null;
552 if (templateFrame == null) {
553 // load in frame.0
554 template = destFramesetZero;
555 } else {
556 template = LoadFrame(templateFrame);
557 if (template == null) {
558 throw new RuntimeException("LinkTemplate " + templateFrame
559 + " could not be found");
560 }
561 }
562
563 ResumeCache();
564
565 // read the next number from the INF file
566 try {
567 next = ReadINF(destFramesetZero.path, frameset);
568 } catch (IOException ioe) {
569 ioe.printStackTrace();
570 throw new RuntimeException("INF file could not be read");
571 }
572
573 // Remove the old frame from the cashe then add the new one
574 // TODO figure out some way that we can put both in the cache
575 _Cache.remove(template.getName().toLowerCase());
576 // set the number and title of the new frame
577 template.setName(frameset, ++next);
578 template.setTitle(frameTitle);
579 // _Cache.put(template.getName().toLowerCase(), template);
580
581 Logger.Log(Logger.SYSTEM, Logger.TDFC, "Creating new frame: "
582 + template.getName() + " from TDFC");
583
584 // update INF file
585 try {
586 WriteINF(template.path, frameset, frameset + next);
587 } catch (IOException ioe) {
588 ioe.printStackTrace();
589 Logger.Log(ioe);
590 }
591
592 template.setOwner(UserSettings.Username);
593 template.resetDateCreated();
594 for (Item i : template.getItems()) {
595 if (ItemUtils.startsWithTag(i, ItemUtils.TAG_PARENT))
596 i.setLink(null);
597 }
598
599 // do auto shrinking of the title IF not in twin frames mode
600 Item titleItem = template.getTitleItem();
601
602 if (!DisplayIO.isTwinFramesOn()) {
603 // BROOK: This had recursion!! Changed to avoid...
604 if ((titleItem.getX() + 1) < template.getNameItem().getX()) {
605 while (titleItem.getBoundsWidth() + titleItem.getX() > template
606 .getNameItem().getX()) {
607 titleItem.setSize(titleItem.getSize() - 1);
608 }
609 } else {
610 System.out.println("Bad title x position: " + titleItem.getX());
611 }
612 }
613 return template;
614 }
615
616 public static void DisableCache() {
617 _UseCache = false;
618 }
619
620 public static void EnableCache() {
621 _UseCache = true;
622 }
623
624 public static void SuspendCache() {
625 if (_UseCache) {
626 DisableCache();
627 _SuspendedCache = true;
628 } else {
629 _SuspendedCache = false;
630 }
631 }
632
633 public static void ResumeCache() {
634 if (_SuspendedCache) {
635 EnableCache();
636 _SuspendedCache = false;
637 }
638 }
639
640 public static void RefreshCasheImages() {
641 SuspendCache();
642 for (Frame f : _Cache.values())
643 f.setBuffer(null);
644 ResumeCache();
645 }
646
647 /**
648 * Creates a new frameset using the given name. This includes creating a new
649 * subdirectory in the <code>FRAME_PATH</code> directory, Copying over the
650 * default.0 frame from the default frameset, copying the .0 Frame to make a
651 * .1 Frame, and creating the frameset's INF file.
652 *
653 * @param frameset
654 * The name of the Frameset to create
655 * @return The first Frame of the new Frameset (Frame.1)
656 */
657 public static Frame CreateFrameset(String frameset, String path)
658 throws Exception {
659 return CreateFrameset(frameset, path, false);
660 }
661
662 /**
663 * Tests if the given String is a 'proper' framename, that is, the String
664 * must begin with a character, end with a number with 0 or more letters and
665 * numbers in between.
666 *
667 * @param frameName
668 * The String to test for validity as a frame name
669 * @return True if the given framename is proper, false otherwise.
670 */
671 public static boolean isValidFrameName(String frameName) {
672
673 if (frameName == null || frameName.length() < 2)
674 return false;
675
676 int lastCharIndex = frameName.length() - 1;
677 // String must begin with a letter and end with a digit
678 if (!Character.isLetter(frameName.charAt(0))
679 || !Character.isDigit(frameName.charAt(lastCharIndex)))
680 return false;
681
682 // All the characters between first and last must be letters
683 // or digits
684 for (int i = 1; i < lastCharIndex; i++) {
685 if (!Character.isLetterOrDigit(frameName.charAt(i)))
686 return false;
687 }
688 return true;
689 }
690
691 /**
692 * Saves the given Frame to disk in the corresponding frameset directory.
693 * This is the same as calling SaveFrame(toSave, true)
694 *
695 * @param toSave
696 * The Frame to save to disk
697 */
698 public static String SaveFrame(Frame toSave) {
699 return SaveFrame(toSave, true);
700 }
701
702 public static String SaveFrame(Frame toSave, boolean inc) {
703 return SaveFrame(toSave, inc, true);
704 }
705
706 /**
707 * Saves the given Frame to disk in the corresponding frameset directory, if
708 * inc is true then the saved frames counter is incremented, otherwise it is
709 * untouched.
710 *
711 * @param toSave
712 * The Frame to save to disk
713 * @param inc
714 * True if the saved frames counter should be incremented, false
715 * otherwise.
716 * @param checkBackup
717 * True if the frame should be checked for the back up tag
718 */
719 public static String SaveFrame(Frame toSave, boolean inc,
720 boolean checkBackup) {
721
722 // TODO When loading a frame maybe append onto the event history too-
723 // with a
724 // break to indicate the end of a session
725
726 if (toSave == null || !toSave.hasChanged() || toSave.isSaved()) {
727 SessionStats.NewFrameSession();
728 return "";
729 }
730 // Get the full path only to determine which format to use for saving
731 // the frame
732 // At this stage use Exp format for saving Exp frames only.
733 // Later this will be changed so that KMS frames will be updated to the
734 // Exp format.
735 String fullPath = getFrameFullPathName(toSave.path, toSave.getName());
736
737 // Dont save if the frame is protected and it exists
738 if (checkBackup && toSave.isReadOnly()) {
739 _Cache.remove(toSave.getName().toLowerCase());
740 SessionStats.NewFrameSession();
741 return "";
742 }
743
744 // Check if the frame exists
745 if (checkBackup && fullPath == null) {
746 // The first time a frame with the backup tag is saved, dont back it
747 // up
748 checkBackup = false;
749 }
750
751 FrameWriter writer = null;
752 int savedVersion;
753 try {
754 // if its a new frame or an existing Exp frame...
755 if (fullPath == null || fullPath.endsWith(ExpReader.EXTENTION)) {
756 writer = new ExpWriter();
757 savedVersion = ExpReader.getVersion(fullPath);
758 } else {
759 writer = new KMSWriter();
760 savedVersion = KMSReader.getVersion(fullPath);
761 }
762 // Check if we are trying to save an out of date version
763 if (savedVersion > toSave.getVersion()
764 && !toSave.getFramesetName().equalsIgnoreCase(
765 MessageBay.MESSAGES_FRAMESET_NAME)) {
766 // remove this frame from the cache if it is there
767 // This will make sure links to the original are set correctly
768 _Cache.remove(toSave.getName().toLowerCase());
769 int nextnum = ReadINF(toSave.path, toSave.getFramesetName()) + 1;
770 SuspendCache();
771 Frame original = LoadFrame(toSave.getName());
772 toSave.setFrameNumber(nextnum);
773 ResumeCache();
774 // Put the modified version in the cache
775 addToCache(toSave);
776 // Show the messages alerting the user
777 Text originalMessage = new Text(-1);
778 originalMessage.setColor(MessageBay.ERROR_COLOR);
779 originalMessage.setText(original.getName()
780 + " was updated by another user.");
781 originalMessage.setLink(original.getName());
782 Text yourMessage = new Text(-1);
783 yourMessage.setColor(MessageBay.ERROR_COLOR);
784 yourMessage.setText("Your version was renamed "
785 + toSave.getName());
786 yourMessage.setLink(toSave.getName());
787 MessageBay.displayMessage(originalMessage);
788 MessageBay.displayMessage(yourMessage);
789 } else if (checkBackup
790 && ItemUtils.ContainsExactTag(toSave.getItems(),
791 ItemUtils.TAG_BACKUP)) {
792 SuspendCache();
793 Frame original = LoadFrame(toSave.getName());
794 if (original == null)
795 original = toSave;
796 int orignum = original.getNumber();
797 int nextnum = ReadINF(toSave.path, toSave.getFramesetName()) + 1;
798
799 original.setFrameNumber(nextnum);
800 original.setPermission(Permission.copy);
801 original.change();
802 SaveFrame(original, false, false);
803
804 Item i = ItemUtils.FindExactTag(toSave.getItems(),
805 ItemUtils.TAG_BACKUP);
806 i.setLink(original.getName());
807 toSave.setFrameNumber(orignum);
808 ResumeCache();
809 }
810 // Update general stuff about frame
811 toSave.setLastModifyDate(Logger.EasyDateFormat("ddMMMyyyy:HHmm"));
812 toSave.setLastModifyUser(UserSettings.Username);
813 toSave.setVersion(toSave.getVersion() + 1);
814 Time darkTime = new Time(SessionStats.getFrameDarkTime().getTime()
815 + toSave.getDarkTime().getTime());
816 Time activeTime = new Time(SessionStats.getFrameActiveTime()
817 .getTime()
818 + toSave.getActiveTime().getTime());
819 toSave.setDarkTime(darkTime);
820 toSave.setActiveTime(activeTime);
821
822 // int oldMode = FrameGraphics.getMode();
823 // if (oldMode != FrameGraphics.MODE_XRAY)
824 // FrameGraphics.setMode(FrameGraphics.MODE_XRAY, true);
825 writer.writeFrame(toSave);
826 // FrameGraphics.setMode(oldMode, true);
827 toSave.setSaved();
828 if (inc) {
829 SessionStats.SavedFrame(toSave.getName());
830 }
831
832 // avoid out-of-sync frames (when in TwinFrames mode)
833 if (_Cache.containsKey(toSave.getName().toLowerCase()))
834 addToCache(toSave);
835
836 Logger.Log(Logger.SYSTEM, Logger.SAVE, "Saving " + toSave.getName()
837 + " to disk.");
838
839 // check that the INF file is not out of date
840 int last = ReadINF(toSave.path, toSave.getFramesetName());
841 if (last <= toSave.getNumber())
842 WriteINF(toSave.path, toSave.getFramesetName(), toSave
843 .getName());
844
845 // check if this was the profile frame (and thus needs
846 // re-parsing)
847 if (isProfileFrame(toSave)) {
848 Frame profile = FrameIO.LoadFrame(toSave.getFramesetName()
849 + "1");
850 assert (profile != null);
851 FrameUtils.ParseProfile(profile);
852 }
853 } catch (IOException ioe) {
854 ioe.getStackTrace();
855 Logger.Log(ioe);
856 return null;
857 }
858
859 return writer.getFileContents();
860 }
861
862 /**
863 * @param toAdd
864 */
865 public static void addToCache(Frame toAdd) {
866 _Cache.put(toAdd.getName().toLowerCase(), toAdd);
867 }
868
869 /**
870 * Checks if a frame is in the current user profile frameset.
871 *
872 * @param toCheck
873 * the frame to check
874 * @return true if the frame is in the current user profile frameset
875 */
876 public static boolean isProfileFrame(Frame toCheck) {
877 if (toCheck.getNumber() == 0)
878 return false;
879 return toCheck.getFramesetName()
880 .equalsIgnoreCase(UserSettings.Username);
881 }
882
883 public static Frame LoadProfile(String userName) {
884 return LoadFrame(userName + "1");
885 }
886
887 public static Frame CreateNewProfile(String username) throws Exception {
888 Frame profile = CreateFrameset(username, PROFILE_PATH, true);
889 FrameUtils.CreateDefaultProfile(profile);
890 return profile;
891 }
892
893 /**
894 * Reads the INF file that corresponds to the given Frame name
895 *
896 * @param framename
897 * The Frame to lookup the INF file for
898 * @throws IOException
899 * Any exceptions encountered by the BufferedReader used to read
900 * the INF.
901 */
902 private static int ReadINF(String path, String frameset) throws IOException {
903 assert (!frameset.endsWith("."));
904
905 // read INF
906 BufferedReader reader;
907 try {
908 reader = new BufferedReader(new FileReader(path
909 + frameset.toLowerCase() + File.separator + INF_FILENAME));
910 } catch (Exception e) {
911 reader = new BufferedReader(new FileReader(path
912 + frameset.toLowerCase() + File.separator
913 + frameset.toLowerCase() + ".inf"));
914 }
915 String inf = reader.readLine();
916 reader.close();
917
918 return Conversion.getFrameNumber(inf);
919 }
920
921 /**
922 * Writes the given String out to the INF file corresponding to the current
923 * frameset.
924 *
925 * @param toWrite
926 * The String to write to the file.
927 * @throws IOException
928 * Any exception encountered by the BufferedWriter.
929 */
930 private static void WriteINF(String path, String frameset, String frameName)
931 throws IOException {
932 assert (!frameset.endsWith("."));
933
934 path += frameset.toLowerCase() + File.separator + INF_FILENAME;
935
936 BufferedWriter writer = new BufferedWriter(new FileWriter(path));
937 writer.write(frameName);
938 writer.close();
939 }
940
941 public static boolean FrameIsCached(String name) {
942 return _Cache.containsKey(name);
943 }
944
945 /**
946 * Gets a frame from the cache.
947 *
948 * @param name
949 * The frame to get from the cache
950 *
951 * @return
952 * The frame from cache. Null if not cached.
953 */
954 public static Frame FrameFromCache(String name) {
955 return _Cache.get(name);
956 }
957
958 public static String ConvertToValidFramesetName(String toValidate) {
959 assert (toValidate != null && toValidate.length() > 0);
960
961 StringBuffer result = new StringBuffer();
962
963 if (Character.isDigit(toValidate.charAt(0))) {
964 result.append(FRAME_NAME_LAST_CHAR);
965 }
966
967 boolean capital = false;
968 for (int i = 0; i < toValidate.length()
969 && result.length() < MAX_NAME_LENGTH; i++) {
970 char cur = toValidate.charAt(i);
971
972 // capitalize all characters after spaces
973 if (Character.isLetterOrDigit(cur)) {
974 if (capital) {
975 capital = false;
976 result.append(Character.toUpperCase(cur));
977 } else
978 result.append(cur);
979 } else {
980 capital = true;
981 }
982 }
983 assert (result.length() > 0);
984 int lastCharIndex = result.length() - 1;
985 if (!Character.isLetter(result.charAt(lastCharIndex))) {
986 if (lastCharIndex == MAX_NAME_LENGTH - 1)
987 result.setCharAt(lastCharIndex, FRAME_NAME_LAST_CHAR);
988 else
989 result.append(FRAME_NAME_LAST_CHAR);
990 }
991
992 assert (isValidFramesetName(result.toString()));
993 return result.toString();
994 }
995
996 public static Frame CreateNewFrame(Item linker) throws RuntimeException {
997 String title = linker.getName();
998
999 String templateLink = linker.getAbsoluteLinkTemplate();
1000 String framesetLink = linker.getAbsoluteLinkFrameset();
1001 String frameset = (framesetLink != null ? framesetLink : DisplayIO
1002 .getCurrentFrame().getFramesetName());
1003
1004 Frame newFrame = FrameIO.CreateFrame(frameset, title, templateLink);
1005 return newFrame;
1006 }
1007
1008 /**
1009 * Creates a new Frameset on disk, including a .0, .1, and .inf files. The
1010 * Default.0 frame is copied to make the initial .0 and .1 Frames
1011 *
1012 * @param name
1013 * The Frameset name to use
1014 * @return The name of the first Frame in the newly created Frameset (the .1
1015 * frame)
1016 */
1017 public static Frame CreateNewFrameset(String name) throws Exception {
1018 String path = DisplayIO.getCurrentFrame().path;
1019
1020 // if current frameset is profile directory change it to framesets
1021 if (path.equals(FrameIO.PROFILE_PATH)) {
1022 path = FrameIO.FRAME_PATH;
1023 }
1024
1025 return FrameIO.CreateFrameset(name, path);
1026 }
1027
1028 /**
1029 *
1030 * @param frameset
1031 * @return
1032 */
1033 public static int getLastNumber(String frameset) { // Rob thinks it might
1034 // have been
1035 // GetHighestNumExFrame
1036 // TODO minimise the number of frames being read in!!
1037 int num = -1;
1038
1039 Frame zero = LoadFrame(frameset + "0");
1040
1041 // the frameset does not exist (or has no 0 frame)
1042 if (zero == null)
1043 return -1;
1044
1045 try {
1046 num = ReadINF(zero.path, frameset);
1047 } catch (IOException e) {
1048 // TODO Auto-generated catch block
1049 // e.printStackTrace();
1050 }
1051
1052 /*
1053 * Michael doesnt think the code below is really needed... it will just
1054 * slow things down when we are reading frames over a network***** for (;
1055 * num >= 0; num--) { System.out.println("This code is loading frames to
1056 * find the highest existing frame..."); if (LoadFrame(frameset + num) !=
1057 * null) break; }
1058 */
1059
1060 return num;
1061 }
1062
1063 /**
1064 * Checks if a given frameset is accessable.
1065 *
1066 * @param framesetName
1067 * @return
1068 */
1069 public static Boolean canAccessFrameset(String framesetName) {
1070 framesetName = framesetName.toLowerCase();
1071 for (String path : UserSettings.FrameDirs) {
1072 if ((new File(path + framesetName)).exists())
1073 return true;
1074 }
1075 return false;
1076 }
1077
1078 public static Frame CreateFrameset(String frameset, String path,
1079 boolean recreate) throws Exception {
1080 String conversion = frameset + " --> ";
1081
1082 if (!isValidFramesetName(frameset)) {
1083 throw new Exception("Invalid frameset name");
1084 }
1085
1086 if (!recreate && FrameIO.canAccessFrameset(frameset)) {
1087 throw new ExistingFramesetException(frameset);
1088 }
1089
1090 conversion += frameset;
1091 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Frameset Name: "
1092 + conversion);
1093 conversion = frameset;
1094
1095 /**
1096 * TODO: Update this to exclude any\all invalid filename characters
1097 */
1098 // ignore annotation character
1099 if (frameset.startsWith("@"))
1100 frameset = frameset.substring(1);
1101
1102 conversion += " --> " + frameset;
1103 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Name: " + conversion);
1104
1105 // create the new Frameset directory
1106 File dir = new File(path + frameset.toLowerCase() + File.separator);
1107
1108 dir.mkdirs();
1109
1110 // create the new INF file
1111 try {
1112 WriteINF(path, frameset, frameset + '1');
1113 } catch (IOException ioe) {
1114 ioe.printStackTrace();
1115 Logger.Log(ioe);
1116 }
1117
1118 SuspendCache();
1119 // copy the default .0 and .1 files
1120 Frame base = null;
1121 try {
1122 base = LoadFrame(UserSettings.DefaultFrame);
1123 } catch (Exception e) {
1124 }
1125 // The frame may not be accessed for various reasons... in all these
1126 // cases just create a new one
1127 if (base == null) {
1128 base = new Frame();
1129 }
1130
1131 ResumeCache();
1132
1133 base.resetDateCreated();
1134 base.setFrameset(frameset);
1135 base.setFrameNumber(0);
1136 base.setTitle(base.getFramesetName() + "0");
1137 base.path = path;
1138 base.change();
1139 SaveFrame(base, false);
1140
1141 base.resetDateCreated();
1142 base.setFrameNumber(1);
1143 base.setTitle(frameset);
1144 base.change();
1145 SaveFrame(base, true);
1146
1147 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Created new frameset: "
1148 + frameset);
1149
1150 return base;
1151 }
1152
1153 /**
1154 * Tests if a frameset name is valid. That is it must begin and end with a
1155 * letter and contain only letters and digits in between.
1156 *
1157 * @param frameset
1158 * the name to be tested
1159 * @return true if the frameset name is valid
1160 */
1161 public static boolean isValidFramesetName(String frameset) {
1162 if (frameset == null) {
1163 return false;
1164 }
1165
1166 int nameLength = frameset.length();
1167 if (frameset.length() <= 0 || nameLength > MAX_NAME_LENGTH) {
1168 return false;
1169 }
1170
1171 int lastCharIndex = nameLength - 1;
1172
1173 if (!Character.isLetter(frameset.charAt(0))
1174 || !Character.isLetter(frameset.charAt(lastCharIndex)))
1175 return false;
1176
1177 for (int i = 1; i < lastCharIndex; i++) {
1178 if (!Character.isLetterOrDigit(frameset.charAt(i))) {
1179 return false;
1180 }
1181 }
1182 return true;
1183 }
1184
1185 public static boolean DeleteFrameset(String framesetName) {
1186 if (!FrameIO.canAccessFrameset(framesetName))
1187 return false;
1188 // Search all the available directories for the directory
1189 for (String path : UserSettings.FrameDirs) {
1190 String source = path + framesetName.toLowerCase() + File.separator;
1191 File framesetDirectory = new File(source);
1192 // Once we have found the directory move it to the trash
1193 if (framesetDirectory.exists()) {
1194 String destPath = FrameIO.TRASH_PATH
1195 + framesetName.toLowerCase();
1196 int copyNumber = 1;
1197 File dest = new File(destPath + File.separator);
1198 // Create the trash folder if it doesnt already exist
1199 if (!dest.getParentFile().exists())
1200 dest.mkdirs();
1201 // If a frameset with the same name is already in the trash add
1202 // a number to the end
1203 while (dest.exists()) {
1204 dest = new File(destPath + ++copyNumber + File.separator);
1205 }
1206 if (!framesetDirectory.renameTo(dest)) {
1207 for (File f : framesetDirectory.listFiles()) {
1208 if (!f.delete())
1209 return false;
1210 }
1211 if (!framesetDirectory.delete())
1212 return false;
1213 }
1214 return true;
1215 }
1216 }
1217 return false;
1218 }
1219
1220 public static boolean CopyFrameset(String framesetToCopy,
1221 String copiedFrameset) throws Exception {
1222 if (!FrameIO.canAccessFrameset(framesetToCopy))
1223 return false;
1224 if (FrameIO.canAccessFrameset(copiedFrameset))
1225 return false;
1226 // search through all the directories to find the frameset we are
1227 // copying
1228 for (String path : UserSettings.FrameDirs) {
1229 String source = path + framesetToCopy.toLowerCase()
1230 + File.separator;
1231 File framesetDirectory = new File(source);
1232 if (framesetDirectory.exists()) {
1233 // copy the frameset
1234 File copyFramesetDirectory = new File(path
1235 + copiedFrameset.toLowerCase() + File.separator);
1236 if (!copyFramesetDirectory.mkdirs())
1237 return false;
1238 // copy each of the frames
1239 for (File f : framesetDirectory.listFiles()) {
1240 // Ignore hidden files
1241 if (f.getName().charAt(0) == '.')
1242 continue;
1243 String copyPath = copyFramesetDirectory.getAbsolutePath()
1244 + File.separator + f.getName();
1245 FrameIO.copyFile(f.getAbsolutePath(), copyPath);
1246 }
1247 return true;
1248 }
1249 }
1250 return false;
1251 }
1252
1253 /**
1254 * Copies a file from one location to another.
1255 *
1256 * @param existingFile
1257 * @param newFileName
1258 * @throws Exception
1259 */
1260 public static void copyFile(String existingFile, String newFileName)
1261 throws Exception {
1262 FileInputStream is = new FileInputStream(existingFile);
1263 FileOutputStream os = new FileOutputStream(newFileName, false);
1264 int data;
1265 while ((data = is.read()) != -1) {
1266 os.write(data);
1267 }
1268 os.flush();
1269 os.close();
1270 is.close();
1271 }
1272
1273 /**
1274 * Saves a frame regardless of whether or not the frame is marked as having
1275 * been changed.
1276 *
1277 * @param frame
1278 * the frame to save
1279 * @return the contents of the frame or null if it could not be saved
1280 */
1281 public static String ForceSaveFrame(Frame frame) {
1282 frame.change();
1283 return SaveFrame(frame, false);
1284 }
1285
1286 public static boolean isValidLink(String frameName) {
1287 return frameName == null || isPositiveInteger(frameName)
1288 || isValidFrameName(frameName);
1289 }
1290
1291}
Note: See TracBrowser for help on using the repository browser.