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

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