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

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

Moved the static field USER_NOBODY to AuthenticatorBrowser from Browser as it makes more sense there.
Added functionality to log out, equiv to closing Expeditee and starting it again.

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