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

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

Amendment to previous commit.

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.


New stuffs.
org.expeditee.gui.FrameIO ->
org.expeditee.io.DefaultFrameReader ->
org.expeditee.io.ExpReader ->

When saving a frame, if there is a newer version (than what is cached) on the file system, then treat that a version collision (creates a new frame with your edits on it so that it can be manually resolved)

File size: 51.2 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 // TODO When loading a frame maybe append onto the event history too-
965 // with a break to indicate the end of a session
966
967 if (toSave == null || !toSave.hasChanged() || toSave.isSaved()) {
968 return "";
969 }
970
971 // Dont save if the frame is protected and it exists
972 if (checkBackup && toSave.isReadOnly()) {
973 _Cache.remove(toSave.getName().toLowerCase());
974 return "";
975 }
976
977 /* Dont save the frame if it has the noSave tag */
978 if (toSave.hasAnnotation("nosave")) {
979 Actions.LegacyPerformActionCatchErrors(toSave, null, "Restore");
980 return "";
981 }
982
983 // Save frame that is not local through the Networking classes
984 // TODO
985 if (!toSave.isLocal()) {
986 return FrameShare.getInstance().saveFrame(toSave);
987 }
988
989 /* Format the frame if it has the autoFormat tag */
990 if (toSave.hasAnnotation("autoformat")) {
991 Actions.LegacyPerformActionCatchErrors(toSave, null, "Format");
992 }
993
994 /**
995 * Get the full path only to determine which format to use for saving
996 * the frame. At this stage use Exp format for saving Exp frames only.
997 * Later this will be changed so that KMS frames will be updated to the
998 * Exp format.
999 */
1000 String fullPath = getFrameFullPathName(toSave.getPath(), toSave
1001 .getName());
1002
1003 // Check if the frame exists
1004 if (checkBackup && fullPath == null) {
1005 // The first time a frame with the backup tag is saved, dont back it
1006 // up
1007 checkBackup = false;
1008 }
1009
1010 FrameWriter writer = null;
1011 int savedVersion;
1012 try {
1013 // if its a new frame or an existing Exp frame...
1014 if (fullPath == null || fullPath.endsWith(ExpReader.EXTENTION)) {
1015 if (UserSettings.Authenticated.get() &&
1016 toSave.getNumber() != Authenticator.PUBLIC_KEY_FRAME &&
1017 toSave.getEncryptionLabel() != null) {
1018 writer = new EncryptedExpWriter(toSave.getEncryptionLabel());
1019 savedVersion = EncryptedExpReader.getVersion(fullPath);
1020 } else {
1021 writer = new ExpWriter();
1022 savedVersion = ExpReader.getVersion(fullPath);
1023 }
1024 } else {
1025 writer = new KMSWriter();
1026 savedVersion = KMSReader.getVersion(fullPath);
1027 }
1028
1029 // Check if the frame doesnt exist
1030 // if (savedVersion < 0) {
1031 // /*
1032 // * This will happen if the user has two Expeditee's running at
1033 // * once and closes the first. When the second one closes the
1034 // * messages directory will have been deleted.
1035 // */
1036 // MessageBay
1037 // .errorMessage("Could not save frame that does not exist: "
1038 // + toSave.getName());
1039 // return null;
1040 // }
1041
1042 // Check if we are trying to save an out of date version
1043 String framesetName = toSave.getFramesetName();
1044 long frameLastModify = toSave.getLastModifyPrecise();
1045 long fileLastModify = new File(fullPath).lastModified();
1046 boolean versionConflict = frameLastModify < fileLastModify;
1047 boolean isBayFrameset =
1048 framesetName.equalsIgnoreCase(MessageBay.MESSAGES_FRAMESET_NAME) ||
1049 framesetName.equalsIgnoreCase(MailBay.EXPEDITEE_MAIL_FRAMESET_NAME);
1050 if ((savedVersion > toSave.getVersion() || versionConflict) && !isBayFrameset) {
1051 // remove this frame from the cache if it is there
1052 // This will make sure links to the original are set correctly
1053 _Cache.remove(toSave.getName().toLowerCase());
1054 int nextnum = ReadINF(toSave.getPath(), toSave
1055 .getFramesetName(), false) + 1;
1056 SuspendCache();
1057 Frame original = LoadFrame(toSave.getName());
1058 toSave.setFrameNumber(nextnum);
1059 ResumeCache();
1060 // Put the modified version in the cache
1061 addToCache(toSave);
1062 // Show the messages alerting the user
1063 Text originalMessage = new Text(-1);
1064 originalMessage.setColor(MessageBay.ERROR_COLOR);
1065 originalMessage.setText(original.getName()
1066 + " was updated by another user.");
1067 originalMessage.setLink(original.getName());
1068 Text yourMessage = new Text(-1);
1069 yourMessage.setColor(MessageBay.ERROR_COLOR);
1070 yourMessage.setText("Your version was renamed "
1071 + toSave.getName());
1072 yourMessage.setLink(toSave.getName());
1073 MessageBay.displayMessage(originalMessage);
1074 MessageBay.displayMessage(yourMessage);
1075 } else if (checkBackup
1076 && ItemUtils.ContainsExactTag(toSave.getItems(),
1077 ItemUtils.TAG_BACKUP)) {
1078 SuspendCache();
1079 String oldFramesetName = toSave.getFramesetName() + "-old";
1080
1081 Frame original = LoadFrame(toSave.getName());
1082 if (original == null) {
1083 original = toSave;
1084 }
1085 int orignum = original.getNumber();
1086
1087 int nextnum = -1;
1088 try {
1089 nextnum = ReadINF(toSave.getPath(), oldFramesetName, false) + 1;
1090 } catch (RuntimeException e) {
1091 try {
1092 CreateFrameset(oldFramesetName, toSave.getPath());
1093 nextnum = 1;
1094 } catch (Exception e1) {
1095 e1.printStackTrace();
1096 }
1097 // e.printStackTrace();
1098 }
1099
1100 if (nextnum > 0) {
1101 original.setFrameset(oldFramesetName);
1102 original.setFrameNumber(nextnum);
1103 original.setPermission(new PermissionPair(UserAppliedPermission.copy));
1104 original.change();
1105 SaveFrame(original, false, false);
1106 }
1107
1108 Item i = ItemUtils.FindExactTag(toSave.getItems(),
1109 ItemUtils.TAG_BACKUP);
1110 i.setLink(original.getName());
1111 toSave.setFrameNumber(orignum);
1112 ResumeCache();
1113 }
1114 // Update general stuff about frame
1115 setSavedProperties(toSave);
1116
1117 // int oldMode = FrameGraphics.getMode();
1118 // if (oldMode != FrameGraphics.MODE_XRAY)
1119 // FrameGraphics.setMode(FrameGraphics.MODE_XRAY, true);
1120 writer.writeFrame(toSave);
1121 // FrameGraphics.setMode(oldMode, true);
1122 toSave.setSaved();
1123 if (inc) {
1124 SessionStats.SavedFrame(toSave.getName());
1125 }
1126
1127 // avoid out-of-sync frames (when in TwinFrames mode)
1128 if (_Cache.containsKey(toSave.getName().toLowerCase())) {
1129 addToCache(toSave);
1130 }
1131
1132 Logger.Log(Logger.SYSTEM, Logger.SAVE, "Saving " + toSave.getName()
1133 + " to disk.");
1134
1135 // check that the INF file is not out of date
1136 int last = ReadINF(toSave.getPath(), toSave.getFramesetName(),
1137 false);
1138 if (last <= toSave.getNumber()) {
1139 WriteINF(toSave.getPath(), toSave.getFramesetName(), toSave
1140 .getName());
1141 }
1142
1143 // check if this was the profile frame (and thus needs
1144 // re-parsing)
1145 if (isProfileFrame(toSave)) {
1146 Frame profile = FrameIO.LoadFrame(toSave.getFramesetName()
1147 + "1");
1148 assert (profile != null);
1149 FrameUtils.ParseProfile(profile);
1150 }
1151 } catch (IOException ioe) {
1152 ioe.printStackTrace();
1153 ioe.getStackTrace();
1154 Logger.Log(ioe);
1155 return null;
1156 }
1157
1158 return writer.getFileContents();
1159 }
1160
1161 /**
1162 * Saves the given Frame to disk in the corresponding frameset directory as a RESTORE, if
1163 * inc is true then the saved frames counter is incremented, otherwise it is
1164 * untouched.
1165 *
1166 * @param toSave
1167 * The Frame to save to disk as the DEFAULT COPY
1168 * @param inc
1169 * True if the saved frames counter should be incremented, false
1170 * otherwise.
1171 * @param checkBackup
1172 * True if the frame should be checked for the back up tag
1173 */
1174 public static String SaveFrameAsRestore(Frame toSave, boolean inc,
1175 boolean checkBackup) {
1176
1177 String sf = SaveFrame(toSave, inc, checkBackup);
1178 String fullPath = getFrameFullPathName(toSave.getPath(), toSave
1179 .getName());
1180 //System.out.println(fullPath);
1181 String restoreVersion = fullPath + ".restore";
1182 File source = new File(fullPath);
1183 File dest = new File(restoreVersion);
1184
1185 FileChannel inputChannel = null;
1186 FileChannel outputChannel = null;
1187
1188 try{
1189 FileInputStream source_fis = new FileInputStream(source);
1190 inputChannel = source_fis.getChannel();
1191
1192 FileOutputStream dest_fos = new FileOutputStream(dest);
1193 outputChannel = dest_fos.getChannel();
1194
1195 outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
1196 inputChannel.close();
1197 outputChannel.close();
1198 source_fis.close();
1199 dest_fos.close();
1200 }
1201 catch(Exception e){
1202 e.printStackTrace();
1203 }
1204
1205 return sf;
1206 }
1207
1208 /**
1209 * @param toAdd
1210 */
1211 public static void addToCache(Frame toAdd) {
1212 _Cache.put(toAdd.getName().toLowerCase(), toAdd);
1213 }
1214
1215 /**
1216 * Checks if a frame is in the current user profile frameset.
1217 *
1218 * @param toCheck
1219 * the frame to check
1220 * @return true if the frame is in the current user profile frameset
1221 */
1222 public static boolean isProfileFrame(Frame toCheck)
1223 {
1224 if (toCheck.getNumber() == 0) {
1225 return false;
1226 }
1227
1228 return toCheck.getPath().equals(PROFILE_PATH);
1229 // return toCheck.getFramesetName()
1230 // .equalsIgnoreCase(UserSettings.ProfileName);
1231 }
1232
1233 public static Frame LoadProfile(String userName)
1234 {
1235 final String profilesLoc = System.getProperty("profiles.loc");
1236 if (profilesLoc != null) {
1237 return LoadFrame(userName + "1", profilesLoc);
1238 } else {
1239 return LoadFrame(userName + "1");
1240 }
1241 }
1242
1243 public static Frame CreateNewProfile(String username) throws Exception {
1244 Frame profile = CreateFrameset(username, PROFILE_PATH, true);
1245 FrameUtils.CreateDefaultProfile(username, profile);
1246 return profile;
1247 }
1248
1249 /**
1250 * Reads the INF file that corresponds to the given Frame name
1251 *
1252 * @param framename
1253 * The Frame to lookup the INF file for
1254 * @throws IOException
1255 * Any exceptions encountered by the BufferedReader used to read
1256 * the INF.
1257 */
1258 public static int ReadINF(String path, String frameset, boolean update)
1259 throws IOException {
1260 assert (!frameset.endsWith("."));
1261 try {
1262 // read INF
1263 BufferedReader reader;
1264 try {
1265 // Check on the local drive
1266 reader = new BufferedReader(new FileReader(path
1267 + frameset.toLowerCase() + File.separator
1268 + INF_FILENAME));
1269 } catch (Exception e) {
1270 reader = new BufferedReader(new FileReader(path
1271 + frameset.toLowerCase() + File.separator
1272 + frameset.toLowerCase() + ".inf"));
1273 }
1274 String inf = reader.readLine();
1275 reader.close();
1276
1277 int next = Conversion.getFrameNumber(inf);
1278 // update INF file
1279 if (update) {
1280 try {
1281 WriteINF(path, frameset, frameset + (next + 1));
1282 } catch (IOException ioe) {
1283 ioe.printStackTrace();
1284 Logger.Log(ioe);
1285 }
1286 }
1287 return next;
1288 } catch (Exception e) {
1289 }
1290
1291 // Check peers
1292 return FrameShare.getInstance().getInfNumber(path, frameset, update);
1293 }
1294
1295 /**
1296 * Writes the given String out to the INF file corresponding to the current
1297 * frameset.
1298 *
1299 * @param toWrite
1300 * The String to write to the file.
1301 * @throws IOException
1302 * Any exception encountered by the BufferedWriter.
1303 */
1304 public static void WriteINF(String path, String frameset, String frameName)
1305 throws IOException {
1306 try {
1307 assert (!frameset.endsWith("."));
1308
1309 path += frameset.toLowerCase() + File.separator + INF_FILENAME;
1310
1311 BufferedWriter writer = new BufferedWriter(new FileWriter(path));
1312 writer.write(frameName);
1313 writer.close();
1314 } catch (Exception e) {
1315
1316 }
1317 }
1318
1319 public static boolean FrameIsCached(String name) {
1320 return _Cache.containsKey(name);
1321 }
1322
1323 /**
1324 * Gets a frame from the cache.
1325 *
1326 * @param name
1327 * The frame to get from the cache
1328 *
1329 * @return The frame from cache. Null if not cached.
1330 */
1331 public static Frame FrameFromCache(String name) {
1332 return _Cache.get(name);
1333 }
1334
1335 public static String ConvertToValidFramesetName(String toValidate) {
1336 assert (toValidate != null && toValidate.length() > 0);
1337
1338 StringBuffer result = new StringBuffer();
1339
1340 if (Character.isDigit(toValidate.charAt(0))) {
1341 result.append(FRAME_NAME_LAST_CHAR);
1342 }
1343
1344 boolean capital = false;
1345 for (int i = 0; i < toValidate.length()
1346 && result.length() < MAX_NAME_LENGTH; i++) {
1347 char cur = toValidate.charAt(i);
1348
1349 // capitalize all characters after spaces
1350 if (Character.isLetterOrDigit(cur)) {
1351 if (capital) {
1352 capital = false;
1353 result.append(Character.toUpperCase(cur));
1354 } else {
1355 result.append(cur);
1356 }
1357 } else {
1358 capital = true;
1359 }
1360 }
1361 assert (result.length() > 0);
1362 int lastCharIndex = result.length() - 1;
1363 if (!Character.isLetter(result.charAt(lastCharIndex))) {
1364 if (lastCharIndex == MAX_NAME_LENGTH - 1) {
1365 result.setCharAt(lastCharIndex, FRAME_NAME_LAST_CHAR);
1366 } else {
1367 result.append(FRAME_NAME_LAST_CHAR);
1368 }
1369 }
1370
1371 assert (isValidFramesetName(result.toString()));
1372 return result.toString();
1373 }
1374
1375 public static Frame CreateNewFrame(Item linker) throws RuntimeException {
1376 String title = linker.getName();
1377
1378 String templateLink = linker.getAbsoluteLinkTemplate();
1379 String framesetLink = linker.getAbsoluteLinkFrameset();
1380 String frameset = (framesetLink != null ? framesetLink : DisplayController
1381 .getCurrentFrame().getFramesetName());
1382
1383 Frame newFrame = FrameIO.CreateFrame(frameset, title, templateLink);
1384 return newFrame;
1385 }
1386
1387 public static Frame CreateNewFrame(Item linker, OnNewFrameAction action) throws RuntimeException {
1388 Frame newFrame = FrameIO.CreateNewFrame(linker);
1389 if(action != null) {
1390 action.exec(linker, newFrame);
1391 }
1392 return newFrame;
1393 }
1394
1395 /**
1396 * Creates a new Frameset on disk, including a .0, .1, and .inf files. The
1397 * Default.0 frame is copied to make the initial .0 and .1 Frames
1398 *
1399 * @param name
1400 * The Frameset name to use
1401 * @return The name of the first Frame in the newly created Frameset (the .1
1402 * frame)
1403 */
1404 public static Frame CreateNewFrameset(String name) throws Exception {
1405 String path = DisplayController.getCurrentFrame().getPath();
1406
1407 // if current frameset is profile directory change it to framesets
1408 if (path.equals(FrameIO.PROFILE_PATH)) {
1409 path = FrameIO.FRAME_PATH;
1410 }
1411
1412 Frame newFrame = FrameIO.CreateFrameset(name, path);
1413
1414 if (newFrame == null) {
1415 // Cant create directories if the path is readonly or there is no
1416 // space available
1417 newFrame = FrameIO.CreateFrameset(name, FrameIO.FRAME_PATH);
1418 }
1419
1420 if (newFrame == null) {
1421 // TODO handle running out of disk space here
1422 }
1423
1424 return newFrame;
1425 }
1426
1427 /**
1428 *
1429 * @param frameset
1430 * @return
1431 */
1432 public static int getLastNumber(String frameset) { // Rob thinks it might
1433 // have been
1434 // GetHighestNumExFrame
1435 // TODO minimise the number of frames being read in!!
1436 int num = -1;
1437
1438 Frame zero = LoadFrame(frameset + "0");
1439
1440 // the frameset does not exist (or has no 0 frame)
1441 if (zero == null) {
1442 return -1;
1443 }
1444
1445 try {
1446 num = ReadINF(zero.getPath(), frameset, false);
1447 } catch (IOException e) {
1448 // TODO Auto-generated catch block
1449 // e.printStackTrace();
1450 }
1451
1452 /*
1453 * Michael doesnt think the code below is really needed... it will just
1454 * slow things down when we are reading frames over a network***** for (;
1455 * num >= 0; num--) { System.out.println("This code is loading frames to
1456 * find the highest existing frame..."); if (LoadFrame(frameset + num) !=
1457 * null) break; }
1458 */
1459
1460 return num;
1461 }
1462
1463 /**
1464 * Checks if a given frameset is accessable.
1465 *
1466 * @param framesetName
1467 * @return
1468 */
1469 public static Boolean canAccessFrameset(String framesetName) {
1470 framesetName = framesetName.toLowerCase();
1471 for (String path : FolderSettings.FrameDirs.get()) {
1472 if ((new File(path + framesetName)).exists()) {
1473 return true;
1474 }
1475 }
1476 return false;
1477 }
1478
1479 public static Frame CreateFrameset(String frameset, String path, boolean recreate) throws Exception
1480 {
1481 String conversion = frameset + " --> ";
1482
1483 if (!isValidFramesetName(frameset)) {
1484 throw new Exception("Invalid frameset name");
1485 }
1486
1487 if (!recreate && FrameIO.canAccessFrameset(frameset)) {
1488 throw new ExistingFramesetException(frameset);
1489 }
1490
1491 conversion += frameset;
1492 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Frameset Name: "
1493 + conversion);
1494 conversion = frameset;
1495
1496 /**
1497 * TODO: Update this to exclude any\all invalid filename characters
1498 */
1499 // ignore annotation character
1500 if (frameset.startsWith("@")) {
1501 frameset = frameset.substring(1);
1502 }
1503
1504 conversion += " --> " + frameset;
1505 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Name: " + conversion);
1506
1507 // create the new Frameset directory
1508 File dir = new File(path + frameset.toLowerCase() + File.separator);
1509
1510 // If the directory doesnt already exist then create it...
1511 if (!dir.exists()) {
1512 // If the directory couldnt be created, then there is something
1513 // wrong... ie. The disk is full.
1514 if (!dir.mkdirs()) {
1515 return null;
1516 }
1517 }
1518
1519 // create the new INF file
1520 try {
1521 WriteINF(path, frameset, frameset + '1');
1522 } catch (IOException ioe) {
1523 ioe.printStackTrace();
1524 Logger.Log(ioe);
1525 }
1526
1527 SuspendCache();
1528 // copy the default .0 and .1 files
1529 Frame base = null;
1530 try {
1531 base = LoadFrame(TemplateSettings.DefaultFrame.get());
1532 } catch (Exception e) {
1533 }
1534 // The frame may not be accessed for various reasons... in all these
1535 // cases just create a new one
1536 if (base == null) {
1537 base = new Frame();
1538 }
1539
1540 ResumeCache();
1541
1542 base.reset();
1543 base.resetDateCreated();
1544 base.setFrameset(frameset);
1545 base.setFrameNumber(0);
1546 base.setTitle(base.getFramesetName() + "0");
1547 base.setPath(path);
1548 base.change();
1549 base.setOwner(UserSettings.UserName.get());
1550 SaveFrame(base, false);
1551
1552 base.reset();
1553 base.resetDateCreated();
1554 base.setFrameNumber(1);
1555 base.setTitle(frameset);
1556 base.change();
1557 base.setOwner(UserSettings.UserName.get());
1558 SaveFrame(base, true);
1559
1560 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Created new frameset: " + frameset);
1561
1562 return base;
1563 }
1564
1565 /**
1566 * Tests if a frameset name is valid. That is it must begin and end with a
1567 * letter and contain only letters and digits in between.
1568 *
1569 * @param frameset
1570 * the name to be tested
1571 * @return true if the frameset name is valid
1572 */
1573 public static boolean isValidFramesetName(String frameset) {
1574 if (frameset == null) {
1575 return false;
1576 }
1577
1578 int nameLength = frameset.length();
1579 if (frameset.length() <= 0 || nameLength > MAX_NAME_LENGTH) {
1580 return false;
1581 }
1582
1583 int lastCharIndex = nameLength - 1;
1584
1585 if (!Character.isLetter(frameset.charAt(0))
1586 || !Character.isLetter(frameset.charAt(lastCharIndex))) {
1587 return false;
1588 }
1589
1590 for (int i = 1; i < lastCharIndex; i++) {
1591 if (!isValidFrameNameChar(frameset.charAt(i))) {
1592 return false;
1593 }
1594 }
1595 return true;
1596 }
1597
1598 public static boolean deleteFrameset(String framesetName) {
1599 return moveFrameset(framesetName, FrameIO.TRASH_PATH);
1600 }
1601
1602 public static boolean moveFrameset(String framesetName,
1603 String destinationFolder) {
1604 if (!FrameIO.canAccessFrameset(framesetName)) {
1605 return false;
1606 }
1607 // Clear the cache
1608 _Cache.clear();
1609
1610 // Search all the available directories for the directory
1611 for (String path : FolderSettings.FrameDirs.get()) {
1612 String source = path + framesetName.toLowerCase() + File.separator;
1613 File framesetDirectory = new File(source);
1614 // Once we have found the directory move it
1615 if (framesetDirectory.exists()) {
1616 String destPath = destinationFolder
1617 + framesetName.toLowerCase();
1618 int copyNumber = 1;
1619 File dest = new File(destPath + File.separator);
1620 // Create the destination folder if it doesnt already exist
1621 if (!dest.getParentFile().exists()) {
1622 dest.mkdirs();
1623 }
1624 // If a frameset with the same name is already in the
1625 // destination add
1626 // a number to the end
1627 while (dest.exists()) {
1628 dest = new File(destPath + ++copyNumber + File.separator);
1629 }
1630 if (!framesetDirectory.renameTo(dest)) {
1631 for (File f : framesetDirectory.listFiles()) {
1632 if (!f.delete()) {
1633 return false;
1634 }
1635 }
1636 if (!framesetDirectory.delete()) {
1637 return false;
1638 }
1639 }
1640 return true;
1641 }
1642 }
1643 return false;
1644 }
1645
1646 public static boolean CopyFrameset(String framesetToCopy,
1647 String copiedFrameset) throws Exception {
1648 if (!FrameIO.canAccessFrameset(framesetToCopy)) {
1649 return false;
1650 }
1651 if (FrameIO.canAccessFrameset(copiedFrameset)) {
1652 return false;
1653 }
1654 // search through all the directories to find the frameset we are
1655 // copying
1656 for (String path : FolderSettings.FrameDirs.get()) {
1657 String source = path + framesetToCopy.toLowerCase()
1658 + File.separator;
1659 File framesetDirectory = new File(source);
1660 if (framesetDirectory.exists()) {
1661 // copy the frameset
1662 File copyFramesetDirectory = new File(path
1663 + copiedFrameset.toLowerCase() + File.separator);
1664 if (!copyFramesetDirectory.mkdirs()) {
1665 return false;
1666 }
1667 // copy each of the frames
1668 for (File f : framesetDirectory.listFiles()) {
1669 // Ignore hidden files
1670 if (f.getName().charAt(0) == '.') {
1671 continue;
1672 }
1673 String copyPath = copyFramesetDirectory.getAbsolutePath()
1674 + File.separator + f.getName();
1675 FrameIO.copyFile(f.getAbsolutePath(), copyPath);
1676 }
1677 return true;
1678 }
1679 }
1680 return false;
1681 }
1682
1683 /**
1684 * Copies a file from one location to another.
1685 *
1686 * @param existingFile
1687 * @param newFileName
1688 * @throws Exception
1689 */
1690 public static void copyFile(String existingFile, String newFileName)
1691 throws IOException {
1692 FileInputStream is = new FileInputStream(existingFile);
1693 FileOutputStream os = new FileOutputStream(newFileName, false);
1694 int data;
1695 while ((data = is.read()) != -1) {
1696 os.write(data);
1697 }
1698 os.flush();
1699 os.close();
1700 is.close();
1701 }
1702
1703 /**
1704 * Saves a frame regardless of whether or not the frame is marked as having
1705 * been changed.
1706 *
1707 * @param frame
1708 * the frame to save
1709 * @return the contents of the frame or null if it could not be saved
1710 */
1711 public static String ForceSaveFrame(Frame frame) {
1712 frame.change();
1713 return SaveFrame(frame, false);
1714 }
1715
1716 public static boolean isValidLink(String frameName) {
1717 return frameName == null || isPositiveInteger(frameName)
1718 || isValidFrameName(frameName);
1719 }
1720
1721 public static void SavePublicFrame(String peerName, String frameName,
1722 int version, BufferedReader packetContents) {
1723 // TODO handle versioning - add version to the header
1724 // Remote user uploads version based on an old version
1725
1726 // Remove it from the cache so that next time it is loaded we get the up
1727 // todate version
1728 _Cache.remove(frameName.toLowerCase());
1729
1730 // Save to file
1731 String filename = PUBLIC_PATH + Conversion.getFramesetName(frameName)
1732 + File.separator + Conversion.getFrameNumber(frameName)
1733 + ExpReader.EXTENTION;
1734
1735 File file = new File(filename);
1736 // Ensure the file exists
1737 if (file.exists()) {
1738 // Check the versions
1739 int savedVersion = ExpReader.getVersion(filename);
1740
1741 if (savedVersion > version) {
1742 // remove this frame from the cache if it is there
1743 // This will make sure links to the original are set correctly
1744 // _Cache.remove(frameName.toLowerCase());
1745
1746 int nextNum = 0;
1747 try {
1748 nextNum = ReadINF(PUBLIC_PATH, Conversion
1749 .getFramesetName(frameName), false) + 1;
1750 } catch (IOException e) {
1751 e.printStackTrace();
1752 }
1753
1754 String newName = Conversion.getFramesetName(frameName)
1755 + nextNum;
1756 filename = PUBLIC_PATH + Conversion.getFramesetName(frameName)
1757 + File.separator + nextNum + ExpReader.EXTENTION;
1758
1759 // Show the messages alerting the user
1760 Text originalMessage = new Text(-1);
1761 originalMessage.setColor(MessageBay.ERROR_COLOR);
1762 originalMessage.setText(frameName + " was edited by "
1763 + peerName);
1764 originalMessage.setLink(frameName);
1765 Text yourMessage = new Text(-1);
1766 yourMessage.setColor(MessageBay.ERROR_COLOR);
1767 yourMessage.setText("Their version was renamed " + newName);
1768 yourMessage.setLink(newName);
1769 MessageBay.displayMessage(originalMessage);
1770 MessageBay.displayMessage(yourMessage);
1771
1772 Frame editedFrame = FrameIO.LoadFrame(frameName);
1773
1774 FrameShare.getInstance().sendMessage(
1775 frameName + " was recently edited by "
1776 + editedFrame.getLastModifyUser(), peerName);
1777 FrameShare.getInstance().sendMessage(
1778 "Your version was renamed " + newName, peerName);
1779 }
1780 }
1781
1782 // Save the new version
1783 try {
1784 // FileWriter fw = new FileWriter(file);
1785
1786 // Open an Output Stream Writer to set encoding
1787 OutputStream fout = new FileOutputStream(file);
1788 OutputStream bout = new BufferedOutputStream(fout);
1789 Writer fw = new OutputStreamWriter(bout, "UTF-8");
1790
1791 String nextLine = null;
1792 while ((nextLine = packetContents.readLine()) != null) {
1793 fw.write(nextLine + '\n');
1794 }
1795 fw.flush();
1796 fw.close();
1797 MessageBay.displayMessage("Saved remote frame: " + frameName);
1798 } catch (IOException e) {
1799 MessageBay.errorMessage("Error remote saving " + frameName + ": "
1800 + e.getMessage());
1801 e.printStackTrace();
1802 }
1803 // } else {
1804 //
1805 //
1806 //
1807 // MessageBay
1808 // .errorMessage("Recieved save request for unknown public frame: "
1809 // + frameName);
1810 // }
1811 }
1812
1813 public static void setSavedProperties(Frame toSave) {
1814 toSave.setLastModifyDate(Formatter.getDateTime(), System.currentTimeMillis());
1815 toSave.setLastModifyUser(UserSettings.UserName.get());
1816 toSave.setVersion(toSave.getVersion() + 1);
1817 Time darkTime = new Time(SessionStats.getFrameDarkTime().getTime()
1818 + toSave.getDarkTime().getTime());
1819 Time activeTime = new Time(SessionStats.getFrameActiveTime().getTime()
1820 + toSave.getActiveTime().getTime());
1821 toSave.setDarkTime(darkTime);
1822 toSave.setActiveTime(activeTime);
1823 }
1824
1825}
Note: See TracBrowser for help on using the repository browser.