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

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

Added debug information to help track down long standing bug.

File size: 60.2 KB
Line 
1/**
2 * FrameIO.java
3 * Copyright (C) 2010 New Zealand Digital Library, http://expeditee.org
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19package org.expeditee.gui;
20
21import java.io.BufferedOutputStream;
22import java.io.BufferedReader;
23import java.io.BufferedWriter;
24import java.io.File;
25import java.io.FileInputStream;
26import java.io.FileNotFoundException;
27import java.io.FileOutputStream;
28import java.io.FileReader;
29import java.io.FileWriter;
30import java.io.IOException;
31import java.io.OutputStream;
32import java.io.OutputStreamWriter;
33import java.io.Writer;
34import java.nio.channels.FileChannel;
35import java.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 System.err.println("Thread name: " + Thread.currentThread().getName());
1187 StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
1188 for (StackTraceElement ste: stackTrace) {
1189 System.err.println(ste.toString());
1190 }
1191 }
1192 if (versionConflict) {
1193 message.append("{ Version conflict }");
1194 }
1195 originalMessage.setText(message.toString());
1196 originalMessage.setLink(original.getName());
1197 Text yourMessage = new Text(-1);
1198 yourMessage.setColor(MessageBay.ERROR_COLOR);
1199 yourMessage.setText("Your version was renamed "
1200 + toSave.getName());
1201 yourMessage.setLink(toSave.getName());
1202 MessageBay.displayMessage(originalMessage);
1203 MessageBay.displayMessage(yourMessage);
1204 EcosystemManager.getMiscManager().beep();
1205 } else if (checkBackup
1206 && ItemUtils.ContainsExactTag(toSave.getItems(),
1207 ItemUtils.TAG_BACKUP)) {
1208 SuspendCache();
1209 String oldFramesetName = toSave.getFramesetName() + "-old";
1210
1211 Frame original = LoadFrame(toSave.getName());
1212 if (original == null) {
1213 original = toSave;
1214 }
1215 int orignum = original.getNumber();
1216
1217 int nextnum = -1;
1218 try {
1219 nextnum = ReadINF(toSave.getPath(), oldFramesetName, false) + 1;
1220 } catch (RuntimeException e) {
1221 try {
1222 CreateFrameset(oldFramesetName, toSave.getPath());
1223 nextnum = 1;
1224 } catch (Exception e1) {
1225 e1.printStackTrace();
1226 }
1227 // e.printStackTrace();
1228 }
1229
1230 if (nextnum > 0) {
1231 original.setFrameset(oldFramesetName);
1232 original.setFrameNumber(nextnum);
1233 original.setPermission(new PermissionPair(UserAppliedPermission.copy));
1234 original.change();
1235 SaveFrame(original, false, false);
1236 }
1237
1238 Item i = ItemUtils.FindExactTag(toSave.getItems(),
1239 ItemUtils.TAG_BACKUP);
1240 i.setLink(original.getName());
1241 toSave.setFrameNumber(orignum);
1242 ResumeCache();
1243 }
1244
1245 // int oldMode = FrameGraphics.getMode();
1246 // if (oldMode != FrameGraphics.MODE_XRAY)
1247 // FrameGraphics.setMode(FrameGraphics.MODE_XRAY, true);
1248
1249 writer.writeFrame(toSave);
1250 // FrameGraphics.setMode(oldMode, true);
1251 toSave.setSaved();
1252
1253 // Update general stuff about frame
1254 setSavedProperties(toSave);
1255
1256 if (inc) {
1257 SessionStats.SavedFrame(toSave.getName());
1258 }
1259
1260 // avoid out-of-sync frames (when in TwinFrames mode)
1261 if (_Cache.containsKey(toSave.getName().toLowerCase())) {
1262 addToCache(toSave);
1263 }
1264
1265 Logger.Log(Logger.SYSTEM, Logger.SAVE, "Saving " + toSave.getName()
1266 + " to disk.");
1267
1268 // check that the INF file is not out of date
1269 int last = ReadINF(toSave.getPath(), toSave.getFramesetName(),
1270 false);
1271 if (last <= toSave.getNumber()) {
1272 WriteINF(toSave.getPath(), toSave.getFramesetName(), toSave
1273 .getName());
1274 }
1275
1276 // check if this was the profile frame (and thus needs
1277 // re-parsing)
1278 if (isProfileFrame(toSave)) {
1279 Frame profile = FrameIO.LoadFrame(toSave.getFramesetName() + "1");
1280 assert (profile != null);
1281 FrameUtils.ParseProfile(profile);
1282 }
1283 } catch (IOException ioe) {
1284 ioe.printStackTrace();
1285 ioe.getStackTrace();
1286 Logger.Log(ioe);
1287 return null;
1288 }
1289 toSave.notifyObservers(false);
1290
1291 return writer.getFileContents();
1292 }
1293
1294 /**
1295 * Saves the given Frame to disk in the corresponding frameset directory as a RESTORE, if
1296 * inc is true then the saved frames counter is incremented, otherwise it is
1297 * untouched.
1298 *
1299 * @param toSave
1300 * The Frame to save to disk as the DEFAULT COPY
1301 * @param inc
1302 * True if the saved frames counter should be incremented, false
1303 * otherwise.
1304 * @param checkBackup
1305 * True if the frame should be checked for the back up tag
1306 */
1307 public static String SaveFrameAsRestore(Frame toSave, boolean inc,
1308 boolean checkBackup) {
1309
1310 String sf = SaveFrame(toSave, inc, checkBackup);
1311 String fullPath = getFrameFullPathName(toSave.getPath(), toSave
1312 .getName());
1313 //System.out.println(fullPath);
1314 String restoreVersion = fullPath + ".restore";
1315 File source = new File(fullPath);
1316 File dest = new File(restoreVersion);
1317
1318 FileChannel inputChannel = null;
1319 FileChannel outputChannel = null;
1320
1321 try{
1322 FileInputStream source_fis = new FileInputStream(source);
1323 inputChannel = source_fis.getChannel();
1324
1325 FileOutputStream dest_fos = new FileOutputStream(dest);
1326 outputChannel = dest_fos.getChannel();
1327
1328 outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
1329 inputChannel.close();
1330 outputChannel.close();
1331 source_fis.close();
1332 dest_fos.close();
1333 }
1334 catch(Exception e){
1335 e.printStackTrace();
1336 }
1337
1338 return sf;
1339 }
1340
1341 /**
1342 * @param toAdd
1343 */
1344 public static void addToCache(Frame toAdd) {
1345 _Cache.put(toAdd.getName().toLowerCase(), toAdd);
1346 }
1347
1348 public static void ClearCache() {
1349 _Cache.clear();
1350 }
1351
1352 /**
1353 * Checks if a frame is in the current user profile frameset.
1354 *
1355 * @param toCheck
1356 * the frame to check
1357 * @return true if the frame is in the current user profile frameset
1358 */
1359 public static boolean isProfileFrame(Frame toCheck)
1360 {
1361 if (toCheck.getNumber() == 0) {
1362 return false;
1363 }
1364
1365 return toCheck.getPath().equals(PROFILE_PATH);
1366 // return toCheck.getFramesetName()
1367 // .equalsIgnoreCase(UserSettings.ProfileName);
1368 }
1369
1370 public static Frame LoadProfile(String userName)
1371 {
1372 final String profilesLoc = System.getProperty("profiles.loc");
1373 if (profilesLoc != null) {
1374 return LoadFrame(userName + "1", profilesLoc);
1375 } else {
1376 return LoadFrame(userName + "1");
1377 }
1378 }
1379
1380 public static Frame CreateNewProfile(String username, Map<String, Setting> initialSettings, Map<String, Consumer<Frame>> toNotifyOnSet) throws InvalidFramesetNameException, ExistingFramesetException {
1381 Frame profile = CreateFrameset(username, PROFILE_PATH, true);
1382 FrameUtils.CreateDefaultProfile(username, profile, initialSettings, toNotifyOnSet);
1383 return profile;
1384 }
1385
1386 /**
1387 * Reads the INF file that corresponds to the given Frame name
1388 *
1389 * @param framename
1390 * The Frame to lookup the INF file for
1391 * @throws IOException
1392 * Any exceptions encountered by the BufferedReader used to read
1393 * the INF.
1394 */
1395 public static int ReadINF(String path, String frameset, boolean update)
1396 throws IOException {
1397 assert (!frameset.endsWith("."));
1398 try {
1399 // read INF
1400 BufferedReader reader;
1401 try {
1402 // Check on the local drive
1403 reader = new BufferedReader(new FileReader(path
1404 + frameset.toLowerCase() + File.separator
1405 + INF_FILENAME));
1406 } catch (Exception e) {
1407 reader = new BufferedReader(new FileReader(path
1408 + frameset.toLowerCase() + File.separator
1409 + frameset.toLowerCase() + ".inf"));
1410 }
1411 String inf = reader.readLine();
1412 reader.close();
1413
1414 int next = Conversion.getFrameNumber(inf);
1415 // update INF file
1416 if (update) {
1417 try {
1418 WriteINF(path, frameset, frameset + (next + 1));
1419 } catch (IOException ioe) {
1420 ioe.printStackTrace();
1421 Logger.Log(ioe);
1422 }
1423 }
1424 return next;
1425 } catch (Exception e) {
1426 }
1427
1428 // Check peers
1429 return FrameShare.getInstance().getInfNumber(path, frameset, update);
1430 }
1431
1432 /**
1433 * Writes the given String out to the INF file corresponding to the current
1434 * frameset.
1435 *
1436 * @param toWrite
1437 * The String to write to the file.
1438 * @throws IOException
1439 * Any exception encountered by the BufferedWriter.
1440 */
1441 public static void WriteINF(String path, String frameset, String frameName)
1442 throws IOException {
1443 try {
1444 assert (!frameset.endsWith("."));
1445
1446 path += frameset.toLowerCase() + File.separator + INF_FILENAME;
1447
1448 BufferedWriter writer = new BufferedWriter(new FileWriter(path));
1449 writer.write(frameName);
1450 writer.close();
1451 } catch (Exception e) {
1452
1453 }
1454 }
1455
1456 public static boolean FrameIsCached(String name) {
1457 return _Cache.containsKey(name);
1458 }
1459
1460 /**
1461 * Gets a frame from the cache.
1462 *
1463 * @param name
1464 * The frame to get from the cache
1465 *
1466 * @return The frame from cache. Null if not cached.
1467 */
1468 public static Frame FrameFromCache(String name) {
1469 return _Cache.get(name);
1470 }
1471
1472 public static String ConvertToValidFramesetName(String toValidate) {
1473 assert (toValidate != null && toValidate.length() > 0);
1474
1475 StringBuffer result = new StringBuffer();
1476
1477 if (Character.isDigit(toValidate.charAt(0))) {
1478 result.append(FRAME_NAME_LAST_CHAR);
1479 }
1480
1481 boolean capital = false;
1482 for (int i = 0; i < toValidate.length()
1483 && result.length() < MAX_NAME_LENGTH; i++) {
1484 char cur = toValidate.charAt(i);
1485
1486 // capitalize all characters after spaces
1487 if (Character.isLetterOrDigit(cur)) {
1488 if (capital) {
1489 capital = false;
1490 result.append(Character.toUpperCase(cur));
1491 } else {
1492 result.append(cur);
1493 }
1494 } else {
1495 capital = true;
1496 }
1497 }
1498 assert (result.length() > 0);
1499 int lastCharIndex = result.length() - 1;
1500 if (!Character.isLetter(result.charAt(lastCharIndex))) {
1501 if (lastCharIndex == MAX_NAME_LENGTH - 1) {
1502 result.setCharAt(lastCharIndex, FRAME_NAME_LAST_CHAR);
1503 } else {
1504 result.append(FRAME_NAME_LAST_CHAR);
1505 }
1506 }
1507
1508 assert (isValidFramesetName(result.toString()));
1509 return result.toString();
1510 }
1511
1512 public static Frame CreateNewFrame(Item linker) throws RuntimeException {
1513 String title = linker.getName();
1514
1515 String templateLink = linker.getAbsoluteLinkTemplate();
1516 String framesetLink = linker.getAbsoluteLinkFrameset();
1517 String frameset = (framesetLink != null ? framesetLink : DisplayController
1518 .getCurrentFrame().getFramesetName());
1519
1520 Frame newFrame = FrameIO.CreateFrame(frameset, title, templateLink);
1521 return newFrame;
1522 }
1523
1524 public static Frame CreateNewFrame(Item linker, OnNewFrameAction action) throws RuntimeException {
1525 Frame newFrame = FrameIO.CreateNewFrame(linker);
1526 if(action != null) {
1527 action.exec(linker, newFrame);
1528 }
1529 return newFrame;
1530 }
1531
1532 /**
1533 * Creates a new Frameset on disk, including a .0, .1, and .inf files. The
1534 * Default.0 frame is copied to make the initial .0 and .1 Frames
1535 *
1536 * @param name
1537 * The Frameset name to use
1538 * @return The name of the first Frame in the newly created Frameset (the .1
1539 * frame)
1540 */
1541 public static Frame CreateNewFrameset(String name) throws Exception {
1542 String path = DisplayController.getCurrentFrame().getPath();
1543
1544 // if current frameset is profile directory change it to framesets
1545 if (path.equals(FrameIO.PROFILE_PATH)) {
1546 path = FrameIO.FRAME_PATH;
1547 }
1548
1549 Frame newFrame = FrameIO.CreateFrameset(name, path);
1550
1551 if (newFrame == null) {
1552 // Cant create directories if the path is readonly or there is no
1553 // space available
1554 newFrame = FrameIO.CreateFrameset(name, FrameIO.FRAME_PATH);
1555 }
1556
1557 if (newFrame == null) {
1558 // TODO handle running out of disk space here
1559 }
1560
1561 return newFrame;
1562 }
1563
1564 /**
1565 *
1566 * @param frameset
1567 * @return
1568 */
1569 public static int getLastNumber(String frameset) { // Rob thinks it might
1570 // have been
1571 // GetHighestNumExFrame
1572 // TODO minimise the number of frames being read in!!
1573 int num = -1;
1574
1575 Frame zero = LoadFrame(frameset + "0");
1576
1577 // the frameset does not exist (or has no 0 frame)
1578 if (zero == null) {
1579 return -1;
1580 }
1581
1582 try {
1583 num = ReadINF(zero.getPath(), frameset, false);
1584 } catch (IOException e) {
1585 // TODO Auto-generated catch block
1586 // e.printStackTrace();
1587 }
1588
1589 /*
1590 * Michael doesnt think the code below is really needed... it will just
1591 * slow things down when we are reading frames over a network***** for (;
1592 * num >= 0; num--) { System.out.println("This code is loading frames to
1593 * find the highest existing frame..."); if (LoadFrame(frameset + num) !=
1594 * null) break; }
1595 */
1596
1597 return num;
1598 }
1599
1600 /**
1601 * Checks if a given frameset is accessable.
1602 *
1603 * @param framesetName
1604 * @return
1605 */
1606 public static boolean canAccessFrameset(String framesetName) {
1607 framesetName = framesetName.toLowerCase();
1608 for (String path : FolderSettings.FrameDirs.getAbsoluteDirs()) {
1609 if (canAccessFrameset(framesetName, Paths.get(path))) {
1610 return true;
1611 }
1612 }
1613 return false;
1614 }
1615
1616 public static boolean canAccessFrameset(String framesetName, Path path) {
1617 File framesetDir = path.resolve(framesetName).toFile();
1618 if (framesetDir.exists() && framesetDir.isDirectory()) {
1619 return true;
1620 } else {
1621 return false;
1622 }
1623 }
1624
1625 public static Frame CreateFrameset(String frameset, String path, boolean recreate) throws InvalidFramesetNameException, ExistingFramesetException {
1626 String conversion = frameset + " --> ";
1627
1628 if (!isValidFramesetName(frameset)) {
1629 throw new InvalidFramesetNameException(frameset);
1630 }
1631
1632 if (!recreate && FrameIO.canAccessFrameset(frameset)) {
1633 throw new ExistingFramesetException(frameset);
1634 }
1635
1636 conversion += frameset;
1637 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Frameset Name: "
1638 + conversion);
1639 conversion = frameset;
1640
1641 /**
1642 * TODO: Update this to exclude any\all invalid filename characters
1643 */
1644 // ignore annotation character
1645 if (frameset.startsWith("@")) {
1646 frameset = frameset.substring(1);
1647 }
1648
1649 conversion += " --> " + frameset;
1650 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Name: " + conversion);
1651
1652 // create the new Frameset directory
1653 File dir = new File(path + frameset.toLowerCase() + File.separator);
1654
1655 // If the directory doesnt already exist then create it...
1656 if (!dir.exists()) {
1657 // If the directory couldnt be created, then there is something
1658 // wrong... ie. The disk is full.
1659 if (!dir.mkdirs()) {
1660 return null;
1661 }
1662 }
1663
1664 // create the new INF file
1665 try {
1666 WriteINF(path, frameset, frameset + '1');
1667 } catch (IOException ioe) {
1668 ioe.printStackTrace();
1669 Logger.Log(ioe);
1670 }
1671
1672 SuspendCache();
1673 // copy the default .0 and .1 files
1674 Frame base = null;
1675 try {
1676 base = LoadFrame(TemplateSettings.DefaultFrame.get());
1677 } catch (Exception e) {
1678 }
1679 // The frame may not be accessed for various reasons... in all these
1680 // cases just create a new one
1681 if (base == null) {
1682 base = new Frame();
1683 }
1684
1685 ResumeCache();
1686
1687 base.reset();
1688 base.resetDateCreated();
1689 base.setFrameset(frameset);
1690 base.setFrameNumber(0);
1691 base.setTitle(base.getFramesetName() + "0");
1692 base.setPath(path);
1693 base.change();
1694 base.setOwner(UserSettings.UserName.get());
1695 SaveFrame(base, false);
1696
1697 base.reset();
1698 base.resetDateCreated();
1699 base.setFrameNumber(1);
1700 base.setTitle(frameset);
1701 base.change();
1702 base.setOwner(UserSettings.UserName.get());
1703 SaveFrame(base, true);
1704
1705 FrameIO.setSavedProperties(base);
1706
1707 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Created new frameset: " + frameset);
1708
1709 return base;
1710 }
1711
1712 /**
1713 * Tests if a frameset name is valid. That is it must begin and end with a
1714 * letter and contain only letters and digits in between.
1715 *
1716 * @param frameset
1717 * the name to be tested
1718 * @return true if the frameset name is valid
1719 */
1720 public static boolean isValidFramesetName(String frameset) {
1721 if (frameset == null) {
1722 return false;
1723 }
1724
1725 int nameLength = frameset.length();
1726 if (frameset.length() <= 0 || nameLength > MAX_NAME_LENGTH) {
1727 return false;
1728 }
1729
1730 int lastCharIndex = nameLength - 1;
1731
1732 if (!Character.isLetter(frameset.charAt(0))
1733 || !Character.isLetter(frameset.charAt(lastCharIndex))) {
1734 return false;
1735 }
1736
1737 for (int i = 1; i < lastCharIndex; i++) {
1738 if (!isValidFrameNameChar(frameset.charAt(i))) {
1739 return false;
1740 }
1741 }
1742 return true;
1743 }
1744
1745 public static boolean deleteFrameset(String framesetName) {
1746 return moveFrameset(framesetName, FrameIO.TRASH_PATH, true);
1747 }
1748
1749 public static boolean moveFrameset(String framesetName, String destinationFolder, boolean override) {
1750 if (!FrameIO.canAccessFrameset(framesetName)) {
1751 return false;
1752 }
1753 // Clear the cache
1754 _Cache.clear();
1755
1756 // Search all the available directories for the directory
1757 for (String path : FolderSettings.FrameDirs.getAbsoluteDirs()) {
1758 return moveFrameset(framesetName, path, destinationFolder, override);
1759 }
1760 return false;
1761 }
1762
1763 public static boolean moveFrameset(String framesetName, String path, String destinationFolder, boolean override) {
1764 String source = path + framesetName.toLowerCase() + File.separator;
1765 File framesetDirectory = new File(source);
1766 // Once we have found the directory move it
1767 if (framesetDirectory.exists()) {
1768 String destPath = destinationFolder
1769 + framesetName.toLowerCase();
1770 int copyNumber = 1;
1771 File dest = new File(destPath + File.separator);
1772 // Create the destination folder if it doesnt already exist
1773 if (!dest.getParentFile().exists()) {
1774 dest.mkdirs();
1775 }
1776 // If a frameset with the same name is already in the
1777 // destination add
1778 // a number to the end
1779 while (dest.exists() && !override) {
1780 dest = new File(destPath + ++copyNumber + File.separator);
1781 }
1782 try {
1783 moveFileTree(framesetDirectory.toPath(), dest.toPath());
1784 } catch (IOException e) {
1785 e.printStackTrace();
1786 return false;
1787 }
1788
1789 for (File f : framesetDirectory.listFiles()) {
1790 if (!f.delete()) {
1791 return false;
1792 }
1793 }
1794 if (!framesetDirectory.delete()) {
1795 return false;
1796 }
1797 return true;
1798 } else {
1799 return false;
1800 }
1801 }
1802
1803 public static boolean CopyFrameset(String framesetToCopy,
1804 String copiedFrameset) throws Exception {
1805 if (!FrameIO.canAccessFrameset(framesetToCopy)) {
1806 return false;
1807 }
1808 if (FrameIO.canAccessFrameset(copiedFrameset)) {
1809 return false;
1810 }
1811 // search through all the directories to find the frameset we are
1812 // copying
1813 for (String path : FolderSettings.FrameDirs.getAbsoluteDirs()) {
1814 String source = path + framesetToCopy.toLowerCase()
1815 + File.separator;
1816 File framesetDirectory = new File(source);
1817 if (framesetDirectory.exists()) {
1818 // copy the frameset
1819 File copyFramesetDirectory = new File(path
1820 + copiedFrameset.toLowerCase() + File.separator);
1821 if (!copyFramesetDirectory.mkdirs()) {
1822 return false;
1823 }
1824 // copy each of the frames
1825 for (File f : framesetDirectory.listFiles()) {
1826 // Ignore hidden files
1827 if (f.getName().charAt(0) == '.') {
1828 continue;
1829 }
1830 String copyPath = copyFramesetDirectory.getAbsolutePath()
1831 + File.separator + f.getName();
1832 FrameIO.copyFile(f.getAbsolutePath(), copyPath);
1833 }
1834 return true;
1835 }
1836 }
1837 return false;
1838 }
1839
1840 /**
1841 * Copies a file from one location to another.
1842 *
1843 * @param existingFile
1844 * @param newFileName
1845 * @throws Exception
1846 */
1847 public static void copyFile(String existingFile, String newFileName)
1848 throws IOException {
1849 FileInputStream is = new FileInputStream(existingFile);
1850 FileOutputStream os = new FileOutputStream(newFileName, false);
1851 int data;
1852 while ((data = is.read()) != -1) {
1853 os.write(data);
1854 }
1855 os.flush();
1856 os.close();
1857 is.close();
1858 }
1859
1860 /**
1861 * Saves a frame regardless of whether or not the frame is marked as having
1862 * been changed.
1863 *
1864 * @param frame
1865 * the frame to save
1866 * @return the contents of the frame or null if it could not be saved
1867 */
1868 public static String ForceSaveFrame(Frame frame) {
1869 frame.change();
1870 return SaveFrame(frame, false);
1871 }
1872
1873 public static boolean isValidLink(String frameName) {
1874 return frameName == null || isPositiveInteger(frameName)
1875 || isValidFrameName(frameName);
1876 }
1877
1878 public static void SavePublicFrame(String peerName, String frameName,
1879 int version, BufferedReader packetContents) {
1880 // TODO handle versioning - add version to the header
1881 // Remote user uploads version based on an old version
1882
1883 // Remove it from the cache so that next time it is loaded we get the up
1884 // todate version
1885 _Cache.remove(frameName.toLowerCase());
1886
1887 // Save to file
1888 String filename = PUBLIC_PATH + Conversion.getFramesetName(frameName)
1889 + File.separator + Conversion.getFrameNumber(frameName)
1890 + ExpReader.EXTENTION;
1891
1892 File file = new File(filename);
1893 // Ensure the file exists
1894 if (file.exists()) {
1895 // Check the versions
1896 int savedVersion = ExpReader.getVersion(filename);
1897
1898 if (savedVersion > version) {
1899 // remove this frame from the cache if it is there
1900 // This will make sure links to the original are set correctly
1901 // _Cache.remove(frameName.toLowerCase());
1902
1903 int nextNum = 0;
1904 try {
1905 nextNum = ReadINF(PUBLIC_PATH, Conversion
1906 .getFramesetName(frameName), false) + 1;
1907 } catch (IOException e) {
1908 e.printStackTrace();
1909 }
1910
1911 String newName = Conversion.getFramesetName(frameName)
1912 + nextNum;
1913 filename = PUBLIC_PATH + Conversion.getFramesetName(frameName)
1914 + File.separator + nextNum + ExpReader.EXTENTION;
1915
1916 // Show the messages alerting the user
1917 Text originalMessage = new Text(-1);
1918 originalMessage.setColor(MessageBay.ERROR_COLOR);
1919 originalMessage.setText(frameName + " was edited by "
1920 + peerName);
1921 originalMessage.setLink(frameName);
1922 Text yourMessage = new Text(-1);
1923 yourMessage.setColor(MessageBay.ERROR_COLOR);
1924 yourMessage.setText("Their version was renamed " + newName);
1925 yourMessage.setLink(newName);
1926 MessageBay.displayMessage(originalMessage);
1927 MessageBay.displayMessage(yourMessage);
1928
1929 Frame editedFrame = FrameIO.LoadFrame(frameName);
1930
1931 FrameShare.getInstance().sendMessage(
1932 frameName + " was recently edited by "
1933 + editedFrame.getLastModifyUser(), peerName);
1934 FrameShare.getInstance().sendMessage(
1935 "Your version was renamed " + newName, peerName);
1936 }
1937 }
1938
1939 // Save the new version
1940 try {
1941 // FileWriter fw = new FileWriter(file);
1942
1943 // Open an Output Stream Writer to set encoding
1944 OutputStream fout = new FileOutputStream(file);
1945 OutputStream bout = new BufferedOutputStream(fout);
1946 Writer fw = new OutputStreamWriter(bout, "UTF-8");
1947
1948 String nextLine = null;
1949 while ((nextLine = packetContents.readLine()) != null) {
1950 fw.write(nextLine + '\n');
1951 }
1952 fw.flush();
1953 fw.close();
1954 MessageBay.displayMessage("Saved remote frame: " + frameName);
1955 } catch (IOException e) {
1956 MessageBay.errorMessage("Error remote saving " + frameName + ": "
1957 + e.getMessage());
1958 e.printStackTrace();
1959 }
1960 }
1961
1962 public static void setSavedProperties(Frame toSave) {
1963 toSave.setLastModifyDate(Formatter.getDateTime(), System.currentTimeMillis());
1964 toSave.setLastModifyUser(UserSettings.UserName.get());
1965 toSave.setVersion(toSave.getVersion() + 1);
1966 Time darkTime = new Time(SessionStats.getFrameDarkTime().getTime()
1967 + toSave.getDarkTime().getTime());
1968 Time activeTime = new Time(SessionStats.getFrameActiveTime().getTime()
1969 + toSave.getActiveTime().getTime());
1970 toSave.setDarkTime(darkTime);
1971 toSave.setActiveTime(activeTime);
1972 }
1973
1974 public static Path setupPersonalResources(String username) {
1975 Path personalResources = Paths.get(FrameIO.PARENT_FOLDER).resolve("resources-" + username);
1976 personalResources.toFile().mkdir();
1977 File[] globalResourcesToCopy = Paths.get(FrameIO.RESOURCES_PRIVATE_PATH).toFile().listFiles();
1978
1979 try {
1980 for (File toCopy: globalResourcesToCopy) {
1981 Path p = Paths.get(toCopy.getAbsolutePath());
1982 if (!p.getFileName().toString().equals(".res") && !p.getFileName().toString().equals("about")) {
1983 moveFileTree(p.toAbsolutePath(), personalResources.resolve(p.getFileName()));
1984 }
1985 }
1986 }
1987 catch (IOException e) {
1988 e.printStackTrace();
1989 personalResources = null;
1990 }
1991
1992 return personalResources;
1993 }
1994
1995 public static void migrateFrame(Frame toMigrate, Path destinationDirectory) {
1996 Path source = Paths.get(toMigrate.getFramePathReal());
1997 String destination = source.relativize(destinationDirectory).toString().substring(3).replace(File.separator, "/");
1998 try {
1999 Files.move(source, destinationDirectory);
2000 } catch (IOException e) {
2001 System.err.println("FrameIO::migrateFrame: failed to migrate from to new location. Message: " + e.getMessage());
2002 return;
2003 }
2004 try {
2005 FileWriter out = new FileWriter(source.toFile());
2006 out.write("REDIRECT:" + destination);
2007 out.flush();
2008 out.close();
2009 } catch (IOException e) {
2010 System.err.println("FrameIO::migrateFrame: failed to update file [" + source + "] to redirect to [" + destination + "] following migration. Message: " + e.getMessage());
2011 }
2012 }
2013
2014 private static void moveFileTree(Path source, Path target) throws IOException {
2015 if (source.toFile().isDirectory()) {
2016 if (!target.toFile().exists()) {
2017 Files.copy(source, target);
2018 }
2019 File[] files = source.toFile().listFiles();
2020 for (File file: files) {
2021 Path asPath = Paths.get(file.getAbsolutePath());
2022 moveFileTree(asPath, target.resolve(asPath.getFileName()));
2023 }
2024 } else {
2025 Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
2026 }
2027 }
2028}
Note: See TracBrowser for help on using the repository browser.