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

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