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

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

Fixed exceptions being thrown incorrectly in following situations:

Incorrect login
Existing account on account creation
ToggleBay action run but not logged in

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