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

Last change on this file since 590 was 590, checked in by jts21, 11 years ago

Don't delete converted frames so there's a backup in case my code breaks and ruins someone's frames

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