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

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

Alteration to previous commit. Had previously made it so that the owner of a item could inject any property regardless of permission. This has been changed to the owner of the item being able to inject specifically a new permission regardless of permission.

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