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

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

org.expeditee.gui.Frame ->
org.expeditee.gui.FrameIO ->

When loading a frame and deciding if the cache should be used, the file system is now consulted to check if there is a more recent version available. If there is then the cache is not used. This is useful for collaborative frame authoring when access to frame is controlled via a system such as google drive.

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