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

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

Added processing for KMS files in FrameIO.searchFrame

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