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

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