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

Last change on this file since 1219 was 1219, checked in by bln4, 5 years ago

FrameIO.java -> Altercation of how frames are discovered during loading process to be more formal. This will likely evolve further.

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