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

Last change on this file since 1330 was 1330, checked in by bln4, 5 years ago
File size: 63.8 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 _UseCache = false;
1025 }
1026
1027 public static void EnableCache() {
1028 _UseCache = true;
1029 }
1030
1031 public static void SuspendCache() {
1032 if (_UseCache) {
1033 DisableCache();
1034 _SuspendedCache = true;
1035 } else {
1036 _SuspendedCache = false;
1037 }
1038 }
1039
1040 public static void ResumeCache() {
1041 if (_SuspendedCache) {
1042 EnableCache();
1043 _SuspendedCache = false;
1044 }
1045 }
1046
1047 public static void RefreshCacheImages()
1048 {
1049 SuspendCache();
1050 for (Frame frame : _Cache.values()) {
1051 frame.setBuffer(null);
1052 }
1053 ResumeCache();
1054 }
1055
1056 /**
1057 * Creates a new frameset using the given name. This includes creating a new
1058 * subdirectory in the <code>FRAME_PATH</code> directory, Copying over the
1059 * default.0 frame from the default frameset, copying the .0 Frame to make a
1060 * .1 Frame, and creating the frameset's INF file.
1061 *
1062 * @param frameset
1063 * The name of the Frameset to create
1064 * @return The first Frame of the new Frameset (Frame.1)
1065 */
1066 public static Frame CreateFrameset(String frameset, String path)
1067 throws Exception {
1068 return CreateFrameset(frameset, path, false);
1069 }
1070
1071 /**
1072 * Tests if the given String is a 'proper' framename, that is, the String
1073 * must begin with a character, end with a number with 0 or more letters and
1074 * numbers in between.
1075 *
1076 * @param frameName
1077 * The String to test for validity as a frame name
1078 * @return True if the given framename is proper, false otherwise.
1079 */
1080 public static boolean isValidFrameName(String frameName) {
1081
1082 if (frameName == null || frameName.length() < 2) {
1083 return false;
1084 }
1085
1086 int lastCharIndex = frameName.length() - 1;
1087 // String must begin with a letter and end with a digit
1088 if (!Character.isLetter(frameName.charAt(0))
1089 || !Character.isDigit(frameName.charAt(lastCharIndex))) {
1090 return false;
1091 }
1092
1093 // All the characters between first and last must be letters
1094 // or digits
1095 for (int i = 1; i < lastCharIndex; i++) {
1096 if (!isValidFrameNameChar(frameName.charAt(i))) {
1097 return false;
1098 }
1099 }
1100 return true;
1101 }
1102
1103 private static boolean isValidFrameNameChar(char c) {
1104 return c == '-' || c == '.' || Character.isLetterOrDigit(c);
1105 }
1106
1107 /**
1108 * Saves the given Frame to disk in the corresponding frameset directory.
1109 * This is the same as calling SaveFrame(toSave, true)
1110 *
1111 * @param toSave
1112 * The Frame to save to disk
1113 */
1114 public static String SaveFrame(Frame toSave) {
1115 return SaveFrame(toSave, true);
1116 }
1117
1118 /**
1119 * Saves a frame.
1120 *
1121 * @param toSave
1122 * the frame to save
1123 * @param inc
1124 * true if the frames counter should be incremented
1125 * @return the text content of the frame
1126 */
1127 public static String SaveFrame(Frame toSave, boolean inc) {
1128 return SaveFrame(toSave, inc, true);
1129 }
1130
1131 /**
1132 * Saves the given Frame to disk in the corresponding frameset directory, if
1133 * inc is true then the saved frames counter is incremented, otherwise it is
1134 * untouched.
1135 *
1136 * @param toSave
1137 * The Frame to save to disk
1138 * @param inc
1139 * True if the saved frames counter should be incremented, false otherwise.
1140 * @param checkBackup
1141 * True if the frame should be checked for the back up tag
1142 */
1143 public static String SaveFrame(Frame toSave, boolean inc, boolean checkBackup) {
1144 // TODO When loading a frame maybe append onto the event history too-
1145 // with a break to indicate the end of a session
1146
1147 if (toSave == null || !toSave.hasChanged() || toSave.isSaved()) {
1148 return "";
1149 }
1150
1151 // Dont save if the frame is protected and it exists
1152 if (checkBackup && toSave.isReadOnly()) {
1153 _Cache.remove(toSave.getName().toLowerCase());
1154 return "";
1155 }
1156
1157 /* Dont save the frame if it has the noSave tag */
1158 if (toSave.hasAnnotation("nosave")) {
1159 Actions.LegacyPerformActionCatchErrors(toSave, null, "Restore");
1160 return "";
1161 }
1162
1163 // Save frame that is not local through the Networking classes
1164 if (!toSave.isLocal()) {
1165 return FrameShare.getInstance().saveFrame(toSave);
1166 }
1167
1168 /* Format the frame if it has the autoFormat tag */
1169 if (toSave.hasAnnotation("autoformat")) {
1170 Actions.LegacyPerformActionCatchErrors(toSave, null, "Format");
1171 }
1172
1173 /**
1174 * Get the full path only to determine which format to use for saving
1175 * the frame. At this stage use Exp format for saving Exp frames only.
1176 * Later this will be changed so that KMS frames will be updated to the
1177 * Exp format.
1178 */
1179 String fullPath = getFrameFullPathName(toSave.getPath(), toSave
1180 .getName());
1181
1182 // Check if the frame exists
1183 if (checkBackup && fullPath == null) {
1184 // The first time a frame with the backup tag is saved, dont back it
1185 // up
1186 checkBackup = false;
1187 }
1188
1189 FrameWriter writer = null;
1190 int savedVersion;
1191 try {
1192 // if its a new frame or an existing Exp frame...
1193 if (fullPath == null || fullPath.endsWith(ExpReader.EXTENTION)) {
1194 if (toSave.getNumber() != AuthenticatorBrowser.CREDENTIALS_FRAME &&
1195 toSave.getEncryptionLabel() != null) {
1196 writer = new EncryptedExpWriter(toSave.getEncryptionLabel());
1197 savedVersion = EncryptedExpReader.getVersion(fullPath);
1198 } else {
1199 writer = new ExpWriter();
1200 savedVersion = ExpReader.getVersion(fullPath);
1201 }
1202
1203 // Is the file this would be saved to a redirect?
1204 String redirectTo = ExpReader.redirectTo(fullPath);
1205 if (redirectTo != null) {
1206 String redirectedPath = toSave.getFramePathReal();
1207 writer.setOutputLocation(redirectedPath);
1208 }
1209
1210 } else {
1211 writer = new KMSWriter();
1212 savedVersion = KMSReader.getVersion(fullPath);
1213 }
1214
1215 // Check if the frame doesnt exist
1216 // if (savedVersion < 0) {
1217 // /*
1218 // * This will happen if the user has two Expeditee's running at
1219 // * once and closes the first. When the second one closes the
1220 // * messages directory will have been deleted.
1221 // */
1222 // MessageBay
1223 // .errorMessage("Could not save frame that does not exist: "
1224 // + toSave.getName());
1225 // return null;
1226 // }
1227
1228 // Check if we are trying to save an out of date version
1229 String framesetName = toSave.getFramesetName();
1230 boolean isBayFrameset =
1231 framesetName.equalsIgnoreCase(MessageBay.MESSAGES_FRAMESET_NAME) ||
1232 framesetName.equalsIgnoreCase(MailBay.EXPEDITEE_MAIL_FRAMESET_NAME);
1233 long frameLastModify = toSave.getLastModifyPrecise();
1234 long fileLastModify = new File(toSave.getFramePathReal()).lastModified();
1235 boolean fileModifyConflict = fileLastModify > frameLastModify && !isBayFrameset;
1236 boolean versionConflict = savedVersion > toSave.getVersion() && !isBayFrameset;
1237 if (fileModifyConflict || versionConflict) {
1238 // remove this frame from the cache if it is there
1239 // This will make sure links to the original are set correctly
1240 _Cache.remove(toSave.getName().toLowerCase());
1241 int nextnum = ReadINF(toSave.getPath(), toSave
1242 .getFramesetName(), false) + 1;
1243 SuspendCache();
1244 Frame original = LoadFrame(toSave.getName());
1245 toSave.setFrameNumber(nextnum);
1246 ResumeCache();
1247 // Put the modified version in the cache
1248 addToCache(toSave);
1249 // Show the messages alerting the user
1250 Text originalMessage = new Text(-1);
1251 originalMessage.setColor(MessageBay.ERROR_COLOR);
1252 StringBuilder message = new StringBuilder(original.getName()
1253 + " was updated by another user. ");
1254 if (fileModifyConflict) {
1255 message.append("{ File modify conflict }");
1256 System.err.println("Thread name: " + Thread.currentThread().getName());
1257 StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
1258 for (StackTraceElement ste: stackTrace) {
1259 System.err.println(ste.toString());
1260 }
1261 }
1262 if (versionConflict) {
1263 message.append("{ Version conflict }");
1264 }
1265 originalMessage.setText(message.toString());
1266 originalMessage.setLink(original.getName());
1267 Text yourMessage = new Text(-1);
1268 yourMessage.setColor(MessageBay.ERROR_COLOR);
1269 yourMessage.setText("Your version was renamed "
1270 + toSave.getName());
1271 yourMessage.setLink(toSave.getName());
1272 MessageBay.displayMessage(originalMessage);
1273 MessageBay.displayMessage(yourMessage);
1274 EcosystemManager.getMiscManager().beep();
1275 } else if (checkBackup
1276 && ItemUtils.ContainsExactTag(toSave.getItems(),
1277 ItemUtils.TAG_BACKUP)) {
1278 SuspendCache();
1279 String oldFramesetName = toSave.getFramesetName() + "-old";
1280
1281 Frame original = LoadFrame(toSave.getName());
1282 if (original == null) {
1283 original = toSave;
1284 }
1285 int orignum = original.getNumber();
1286
1287 int nextnum = -1;
1288 try {
1289 nextnum = ReadINF(toSave.getPath(), oldFramesetName, false) + 1;
1290 } catch (RuntimeException e) {
1291 try {
1292 CreateFrameset(oldFramesetName, toSave.getPath());
1293 nextnum = 1;
1294 } catch (Exception e1) {
1295 e1.printStackTrace();
1296 }
1297 // e.printStackTrace();
1298 }
1299
1300 if (nextnum > 0) {
1301 original.setFrameset(oldFramesetName);
1302 original.setFrameNumber(nextnum);
1303 original.setPermission(new PermissionPair(UserAppliedPermission.copy));
1304 original.change();
1305 SaveFrame(original, false, false);
1306 }
1307
1308 Item i = ItemUtils.FindExactTag(toSave.getItems(),
1309 ItemUtils.TAG_BACKUP);
1310 i.setLink(original.getName());
1311 toSave.setFrameNumber(orignum);
1312 ResumeCache();
1313 }
1314
1315 // int oldMode = FrameGraphics.getMode();
1316 // if (oldMode != FrameGraphics.MODE_XRAY)
1317 // FrameGraphics.setMode(FrameGraphics.MODE_XRAY, true);
1318
1319 writer.writeFrame(toSave);
1320 // FrameGraphics.setMode(oldMode, true);
1321 toSave.setSaved();
1322
1323 // Update general stuff about frame
1324 setSavedProperties(toSave);
1325
1326 if (inc) {
1327 SessionStats.SavedFrame(toSave.getName());
1328 }
1329
1330 // avoid out-of-sync frames (when in TwinFrames mode)
1331 if (_Cache.containsKey(toSave.getName().toLowerCase())) {
1332 addToCache(toSave);
1333 }
1334
1335 Logger.Log(Logger.SYSTEM, Logger.SAVE, "Saving " + toSave.getName()
1336 + " to disk.");
1337
1338 // check that the INF file is not out of date
1339 int last = ReadINF(toSave.getPath(), toSave.getFramesetName(),
1340 false);
1341 if (last <= toSave.getNumber()) {
1342 WriteINF(toSave.getPath(), toSave.getFramesetName(), toSave
1343 .getName());
1344 }
1345
1346 // check if this was the profile frame (and thus needs
1347 // re-parsing)
1348 if (isProfileFrame(toSave)) {
1349 Frame profile = FrameIO.LoadFrame(toSave.getFramesetName() + "1");
1350 assert (profile != null);
1351 FrameUtils.ParseProfile(profile);
1352 }
1353 } catch (IOException ioe) {
1354 ioe.printStackTrace();
1355 ioe.getStackTrace();
1356 Logger.Log(ioe);
1357 return null;
1358 }
1359 toSave.notifyObservers(false);
1360
1361 return writer.getFileContents();
1362 }
1363
1364 /**
1365 * Saves the given Frame to disk in the corresponding frameset directory as a RESTORE, if
1366 * inc is true then the saved frames counter is incremented, otherwise it is
1367 * untouched.
1368 *
1369 * @param toSave
1370 * The Frame to save to disk as the DEFAULT COPY
1371 * @param inc
1372 * True if the saved frames counter should be incremented, false
1373 * otherwise.
1374 * @param checkBackup
1375 * True if the frame should be checked for the back up tag
1376 */
1377 public static String SaveFrameAsRestore(Frame toSave, boolean inc,
1378 boolean checkBackup) {
1379
1380 String sf = SaveFrame(toSave, inc, checkBackup);
1381 String fullPath = getFrameFullPathName(toSave.getPath(), toSave
1382 .getName());
1383 //System.out.println(fullPath);
1384 String restoreVersion = fullPath + ".restore";
1385 File source = new File(fullPath);
1386 File dest = new File(restoreVersion);
1387
1388 FileChannel inputChannel = null;
1389 FileChannel outputChannel = null;
1390
1391 try{
1392 FileInputStream source_fis = new FileInputStream(source);
1393 inputChannel = source_fis.getChannel();
1394
1395 FileOutputStream dest_fos = new FileOutputStream(dest);
1396 outputChannel = dest_fos.getChannel();
1397
1398 outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
1399 inputChannel.close();
1400 outputChannel.close();
1401 source_fis.close();
1402 dest_fos.close();
1403 }
1404 catch(Exception e){
1405 e.printStackTrace();
1406 }
1407
1408 return sf;
1409 }
1410
1411 /**
1412 * @param toAdd
1413 */
1414 public static void addToCache(Frame toAdd) {
1415 _Cache.put(toAdd.getName().toLowerCase(), toAdd);
1416 }
1417
1418 public static void ClearCache() {
1419 _Cache.clear();
1420 }
1421
1422 /**
1423 * Checks if a frame is in the current user profile frameset.
1424 *
1425 * @param toCheck
1426 * the frame to check
1427 * @return true if the frame is in the current user profile frameset
1428 */
1429 public static boolean isProfileFrame(Frame toCheck)
1430 {
1431 if (toCheck.getNumber() == 0) {
1432 return false;
1433 }
1434
1435 return toCheck.getPath().equals(PROFILE_PATH);
1436 // return toCheck.getFramesetName()
1437 // .equalsIgnoreCase(UserSettings.ProfileName);
1438 }
1439
1440 public static Frame LoadProfile(String userName)
1441 {
1442 final String profilesLoc = System.getProperty("profiles.loc");
1443 if (profilesLoc != null) {
1444 return LoadFrame(userName + "1", profilesLoc);
1445 } else {
1446 return LoadFrame(userName + "1");
1447 }
1448 }
1449
1450 public static Frame CreateNewProfile(String username, Map<String, Setting> initialSettings, Map<String, Consumer<Frame>> toNotifyOnSet) throws InvalidFramesetNameException, ExistingFramesetException {
1451 Frame profile = CreateFrameset(username, PROFILE_PATH, true);
1452 FrameUtils.CreateDefaultProfile(username, profile, initialSettings, toNotifyOnSet);
1453 return profile;
1454 }
1455
1456 /**
1457 * Reads the INF file that corresponds to the given Frame name
1458 *
1459 * @param framename
1460 * The Frame to lookup the INF file for
1461 * @throws IOException
1462 * Any exceptions encountered by the BufferedReader used to read
1463 * the INF.
1464 */
1465 public static int ReadINF(String path, String frameset, boolean update)
1466 throws IOException {
1467 assert (!frameset.endsWith("."));
1468 try {
1469 // read INF
1470 BufferedReader reader;
1471 try {
1472 // Check on the local drive
1473 reader = new BufferedReader(new FileReader(path
1474 + frameset.toLowerCase() + File.separator
1475 + INF_FILENAME));
1476 } catch (Exception e) {
1477 reader = new BufferedReader(new FileReader(path
1478 + frameset.toLowerCase() + File.separator
1479 + frameset.toLowerCase() + ".inf"));
1480 }
1481 String inf = reader.readLine();
1482 reader.close();
1483
1484 int next = Conversion.getFrameNumber(inf);
1485 // update INF file
1486 if (update) {
1487 try {
1488 WriteINF(path, frameset, frameset + (next + 1));
1489 } catch (IOException ioe) {
1490 ioe.printStackTrace();
1491 Logger.Log(ioe);
1492 }
1493 }
1494 return next;
1495 } catch (Exception e) {
1496 }
1497
1498 // Check peers
1499 return FrameShare.getInstance().getInfNumber(path, frameset, update);
1500 }
1501
1502 /**
1503 * Writes the given String out to the INF file corresponding to the current
1504 * frameset.
1505 *
1506 * @param toWrite
1507 * The String to write to the file.
1508 * @throws IOException
1509 * Any exception encountered by the BufferedWriter.
1510 */
1511 public static void WriteINF(String path, String frameset, String frameName)
1512 throws IOException {
1513 try {
1514 assert (!frameset.endsWith("."));
1515
1516 path += frameset.toLowerCase() + File.separator + INF_FILENAME;
1517
1518 BufferedWriter writer = new BufferedWriter(new FileWriter(path));
1519 writer.write(frameName);
1520 writer.close();
1521 } catch (Exception e) {
1522
1523 }
1524 }
1525
1526 public static boolean FrameIsCached(String name) {
1527 return _Cache.containsKey(name);
1528 }
1529
1530 /**
1531 * Gets a frame from the cache.
1532 *
1533 * @param name
1534 * The frame to get from the cache
1535 *
1536 * @return The frame from cache. Null if not cached.
1537 */
1538 public static Frame FrameFromCache(String name) {
1539 return _Cache.get(name);
1540 }
1541
1542 public static String ConvertToValidFramesetName(String toValidate) {
1543 assert (toValidate != null && toValidate.length() > 0);
1544
1545 StringBuffer result = new StringBuffer();
1546
1547 if (Character.isDigit(toValidate.charAt(0))) {
1548 result.append(FRAME_NAME_LAST_CHAR);
1549 }
1550
1551 boolean capital = false;
1552 for (int i = 0; i < toValidate.length()
1553 && result.length() < MAX_NAME_LENGTH; i++) {
1554 char cur = toValidate.charAt(i);
1555
1556 // capitalize all characters after spaces
1557 if (Character.isLetterOrDigit(cur)) {
1558 if (capital) {
1559 capital = false;
1560 result.append(Character.toUpperCase(cur));
1561 } else {
1562 result.append(cur);
1563 }
1564 } else {
1565 capital = true;
1566 }
1567 }
1568 assert (result.length() > 0);
1569 int lastCharIndex = result.length() - 1;
1570 if (!Character.isLetter(result.charAt(lastCharIndex))) {
1571 if (lastCharIndex == MAX_NAME_LENGTH - 1) {
1572 result.setCharAt(lastCharIndex, FRAME_NAME_LAST_CHAR);
1573 } else {
1574 result.append(FRAME_NAME_LAST_CHAR);
1575 }
1576 }
1577
1578 assert (isValidFramesetName(result.toString()));
1579 return result.toString();
1580 }
1581
1582 public static Frame CreateNewFrame(Item linker) throws RuntimeException {
1583 String title = linker.getName();
1584
1585 String templateLink = linker.getAbsoluteLinkTemplate();
1586 String framesetLink = linker.getAbsoluteLinkFrameset();
1587 String frameset = (framesetLink != null ? framesetLink : DisplayController
1588 .getCurrentFrame().getFramesetName());
1589
1590 Frame newFrame = FrameIO.CreateFrame(frameset, title, templateLink);
1591 return newFrame;
1592 }
1593
1594 public static Frame CreateNewFrame(Item linker, OnNewFrameAction action) throws RuntimeException {
1595 Frame newFrame = FrameIO.CreateNewFrame(linker);
1596 if(action != null) {
1597 action.exec(linker, newFrame);
1598 }
1599 return newFrame;
1600 }
1601
1602 /**
1603 * Creates a new Frameset on disk, including a .0, .1, and .inf files. The
1604 * Default.0 frame is copied to make the initial .0 and .1 Frames
1605 *
1606 * @param name
1607 * The Frameset name to use
1608 * @return The name of the first Frame in the newly created Frameset (the .1
1609 * frame)
1610 */
1611 public static Frame CreateNewFrameset(String name) throws Exception {
1612 String path = DisplayController.getCurrentFrame().getPath();
1613
1614 // if current frameset is profile directory change it to framesets
1615 if (path.equals(FrameIO.PROFILE_PATH)) {
1616 path = FrameIO.FRAME_PATH;
1617 }
1618
1619 Frame newFrame = FrameIO.CreateFrameset(name, path);
1620
1621 if (newFrame == null) {
1622 // Cant create directories if the path is readonly or there is no
1623 // space available
1624 newFrame = FrameIO.CreateFrameset(name, FrameIO.FRAME_PATH);
1625 }
1626
1627 if (newFrame == null) {
1628 // TODO handle running out of disk space here
1629 }
1630
1631 return newFrame;
1632 }
1633
1634 /**
1635 *
1636 * @param frameset
1637 * @return
1638 */
1639 public static int getLastNumber(String frameset) { // Rob thinks it might
1640 // have been
1641 // GetHighestNumExFrame
1642 // TODO minimise the number of frames being read in!!
1643 int num = -1;
1644
1645 Frame zero = LoadFrame(frameset + "0");
1646
1647 // the frameset does not exist (or has no 0 frame)
1648 if (zero == null) {
1649 return -1;
1650 }
1651
1652 try {
1653 num = ReadINF(zero.getPath(), frameset, false);
1654 } catch (IOException e) {
1655 // TODO Auto-generated catch block
1656 // e.printStackTrace();
1657 }
1658
1659 /*
1660 * Michael doesnt think the code below is really needed... it will just
1661 * slow things down when we are reading frames over a network***** for (;
1662 * num >= 0; num--) { System.out.println("This code is loading frames to
1663 * find the highest existing frame..."); if (LoadFrame(frameset + num) !=
1664 * null) break; }
1665 */
1666
1667 return num;
1668 }
1669
1670 /**
1671 * Checks if a given frameset is accessable.
1672 *
1673 * @param framesetName
1674 * @return
1675 */
1676 public static boolean canAccessFrameset(String framesetName) {
1677 framesetName = framesetName.toLowerCase();
1678 for (String path : FolderSettings.FrameDirs.getAbsoluteDirs()) {
1679 if (canAccessFrameset(framesetName, Paths.get(path))) {
1680 return true;
1681 }
1682 }
1683 return false;
1684 }
1685
1686 public static boolean canAccessFrameset(String framesetName, Path path) {
1687 File framesetDir = path.resolve(framesetName).toFile();
1688 if (framesetDir.exists() && framesetDir.isDirectory()) {
1689 return true;
1690 } else {
1691 return false;
1692 }
1693 }
1694
1695 public static Frame CreateFrameset(String frameset, String path, boolean recreate) throws InvalidFramesetNameException, ExistingFramesetException {
1696 String conversion = frameset + " --> ";
1697
1698 if (!isValidFramesetName(frameset)) {
1699 throw new InvalidFramesetNameException(frameset);
1700 }
1701
1702 if (!recreate && FrameIO.canAccessFrameset(frameset)) {
1703 throw new ExistingFramesetException(frameset);
1704 }
1705
1706 conversion += frameset;
1707 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Frameset Name: "
1708 + conversion);
1709 conversion = frameset;
1710
1711 /**
1712 * TODO: Update this to exclude any\all invalid filename characters
1713 */
1714 // ignore annotation character
1715 if (frameset.startsWith("@")) {
1716 frameset = frameset.substring(1);
1717 }
1718
1719 conversion += " --> " + frameset;
1720 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Name: " + conversion);
1721
1722 // create the new Frameset directory
1723 File dir = new File(path + frameset.toLowerCase() + File.separator);
1724
1725 // If the directory doesnt already exist then create it...
1726 if (!dir.exists()) {
1727 // If the directory couldnt be created, then there is something
1728 // wrong... ie. The disk is full.
1729 if (!dir.mkdirs()) {
1730 return null;
1731 }
1732 }
1733
1734 // create the new INF file
1735 try {
1736 WriteINF(path, frameset, frameset + '1');
1737 } catch (IOException ioe) {
1738 ioe.printStackTrace();
1739 Logger.Log(ioe);
1740 }
1741
1742 SuspendCache();
1743 // copy the default .0 and .1 files
1744 Frame base = null;
1745 try {
1746 base = LoadFrame(TemplateSettings.DefaultFrame.get());
1747 } catch (Exception e) {
1748 }
1749 // The frame may not be accessed for various reasons... in all these
1750 // cases just create a new one
1751 if (base == null) {
1752 base = new Frame();
1753 }
1754
1755 ResumeCache();
1756
1757 base.reset();
1758 base.resetDateCreated();
1759 base.setFrameset(frameset);
1760 base.setFrameNumber(0);
1761 base.setTitle(base.getFramesetName() + "0");
1762 base.setPath(path);
1763 base.change();
1764 base.setOwner(UserSettings.UserName.get());
1765 SaveFrame(base, false);
1766
1767 base.reset();
1768 base.resetDateCreated();
1769 base.setFrameNumber(1);
1770 base.setTitle(frameset);
1771 base.change();
1772 base.setOwner(UserSettings.UserName.get());
1773 SaveFrame(base, true);
1774
1775 FrameIO.setSavedProperties(base);
1776
1777 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Created new frameset: " + frameset);
1778
1779 return base;
1780 }
1781
1782 /**
1783 * Tests if a frameset name is valid. That is it must begin and end with a
1784 * letter and contain only letters and digits in between.
1785 *
1786 * @param frameset
1787 * the name to be tested
1788 * @return true if the frameset name is valid
1789 */
1790 public static boolean isValidFramesetName(String frameset) {
1791 if (frameset == null) {
1792 return false;
1793 }
1794
1795 int nameLength = frameset.length();
1796 if (frameset.length() <= 0 || nameLength > MAX_NAME_LENGTH) {
1797 return false;
1798 }
1799
1800 int lastCharIndex = nameLength - 1;
1801
1802 if (!Character.isLetter(frameset.charAt(0))
1803 || !Character.isLetter(frameset.charAt(lastCharIndex))) {
1804 return false;
1805 }
1806
1807 for (int i = 1; i < lastCharIndex; i++) {
1808 if (!isValidFrameNameChar(frameset.charAt(i))) {
1809 return false;
1810 }
1811 }
1812 return true;
1813 }
1814
1815 public static boolean deleteFrameset(String framesetName) {
1816 return moveFrameset(framesetName, FrameIO.TRASH_PATH, true);
1817 }
1818
1819 public static boolean moveFrameset(String framesetName, String destinationFolder, boolean override) {
1820 if (!FrameIO.canAccessFrameset(framesetName)) {
1821 return false;
1822 }
1823 // Clear the cache
1824 _Cache.clear();
1825
1826 // Search all the available directories for the directory
1827 for (String path : FolderSettings.FrameDirs.getAbsoluteDirs()) {
1828 return moveFrameset(framesetName, path, destinationFolder, override);
1829 }
1830 return false;
1831 }
1832
1833 public static boolean moveFrameset(String framesetName, String path, String destinationFolder, boolean override) {
1834 String source = path + framesetName.toLowerCase() + File.separator;
1835 File framesetDirectory = new File(source);
1836 // Once we have found the directory move it
1837 if (framesetDirectory.exists()) {
1838 String destPath = destinationFolder
1839 + framesetName.toLowerCase();
1840 int copyNumber = 1;
1841 File dest = new File(destPath + File.separator);
1842 // Create the destination folder if it doesnt already exist
1843 if (!dest.getParentFile().exists()) {
1844 dest.mkdirs();
1845 }
1846 // If a frameset with the same name is already in the
1847 // destination add
1848 // a number to the end
1849 while (dest.exists() && !override) {
1850 dest = new File(destPath + ++copyNumber + File.separator);
1851 }
1852 try {
1853 moveFileTree(framesetDirectory.toPath(), dest.toPath());
1854 } catch (IOException e) {
1855 e.printStackTrace();
1856 return false;
1857 }
1858
1859 for (File f : framesetDirectory.listFiles()) {
1860 if (!f.delete()) {
1861 return false;
1862 }
1863 }
1864 if (!framesetDirectory.delete()) {
1865 return false;
1866 }
1867 return true;
1868 } else {
1869 return false;
1870 }
1871 }
1872
1873 public static boolean CopyFrameset(String framesetToCopy,
1874 String copiedFrameset) throws Exception {
1875 if (!FrameIO.canAccessFrameset(framesetToCopy)) {
1876 return false;
1877 }
1878 if (FrameIO.canAccessFrameset(copiedFrameset)) {
1879 return false;
1880 }
1881 // search through all the directories to find the frameset we are
1882 // copying
1883 for (String path : FolderSettings.FrameDirs.getAbsoluteDirs()) {
1884 String source = path + framesetToCopy.toLowerCase()
1885 + File.separator;
1886 File framesetDirectory = new File(source);
1887 if (framesetDirectory.exists()) {
1888 // copy the frameset
1889 File copyFramesetDirectory = new File(path
1890 + copiedFrameset.toLowerCase() + File.separator);
1891 if (!copyFramesetDirectory.mkdirs()) {
1892 return false;
1893 }
1894 // copy each of the frames
1895 for (File f : framesetDirectory.listFiles()) {
1896 // Ignore hidden files
1897 if (f.getName().charAt(0) == '.') {
1898 continue;
1899 }
1900 String copyPath = copyFramesetDirectory.getAbsolutePath()
1901 + File.separator + f.getName();
1902 FrameIO.copyFile(f.getAbsolutePath(), copyPath);
1903 }
1904 return true;
1905 }
1906 }
1907 return false;
1908 }
1909
1910 /**
1911 * Copies a file from one location to another.
1912 *
1913 * @param existingFile
1914 * @param newFileName
1915 * @throws Exception
1916 */
1917 public static void copyFile(String existingFile, String newFileName)
1918 throws IOException {
1919 FileInputStream is = new FileInputStream(existingFile);
1920 FileOutputStream os = new FileOutputStream(newFileName, false);
1921 int data;
1922 while ((data = is.read()) != -1) {
1923 os.write(data);
1924 }
1925 os.flush();
1926 os.close();
1927 is.close();
1928 }
1929
1930 /**
1931 * Saves a frame regardless of whether or not the frame is marked as having
1932 * been changed.
1933 *
1934 * @param frame
1935 * the frame to save
1936 * @return the contents of the frame or null if it could not be saved
1937 */
1938 public static String ForceSaveFrame(Frame frame) {
1939 frame.change();
1940 return SaveFrame(frame, false);
1941 }
1942
1943 public static boolean isValidLink(String frameName) {
1944 return frameName == null || isPositiveInteger(frameName)
1945 || isValidFrameName(frameName);
1946 }
1947
1948 public static void SavePublicFrame(String peerName, String frameName,
1949 int version, BufferedReader packetContents) {
1950 // TODO handle versioning - add version to the header
1951 // Remote user uploads version based on an old version
1952
1953 // Remove it from the cache so that next time it is loaded we get the up
1954 // todate version
1955 _Cache.remove(frameName.toLowerCase());
1956
1957 // Save to file
1958 String filename = PUBLIC_PATH + Conversion.getFramesetName(frameName)
1959 + File.separator + Conversion.getFrameNumber(frameName)
1960 + ExpReader.EXTENTION;
1961
1962 File file = new File(filename);
1963 // Ensure the file exists
1964 if (file.exists()) {
1965 // Check the versions
1966 int savedVersion = ExpReader.getVersion(filename);
1967
1968 if (savedVersion > version) {
1969 // remove this frame from the cache if it is there
1970 // This will make sure links to the original are set correctly
1971 // _Cache.remove(frameName.toLowerCase());
1972
1973 int nextNum = 0;
1974 try {
1975 nextNum = ReadINF(PUBLIC_PATH, Conversion
1976 .getFramesetName(frameName), false) + 1;
1977 } catch (IOException e) {
1978 e.printStackTrace();
1979 }
1980
1981 String newName = Conversion.getFramesetName(frameName)
1982 + nextNum;
1983 filename = PUBLIC_PATH + Conversion.getFramesetName(frameName)
1984 + File.separator + nextNum + ExpReader.EXTENTION;
1985
1986 // Show the messages alerting the user
1987 Text originalMessage = new Text(-1);
1988 originalMessage.setColor(MessageBay.ERROR_COLOR);
1989 originalMessage.setText(frameName + " was edited by "
1990 + peerName);
1991 originalMessage.setLink(frameName);
1992 Text yourMessage = new Text(-1);
1993 yourMessage.setColor(MessageBay.ERROR_COLOR);
1994 yourMessage.setText("Their version was renamed " + newName);
1995 yourMessage.setLink(newName);
1996 MessageBay.displayMessage(originalMessage);
1997 MessageBay.displayMessage(yourMessage);
1998
1999 Frame editedFrame = FrameIO.LoadFrame(frameName);
2000
2001 FrameShare.getInstance().sendMessage(
2002 frameName + " was recently edited by "
2003 + editedFrame.getLastModifyUser(), peerName);
2004 FrameShare.getInstance().sendMessage(
2005 "Your version was renamed " + newName, peerName);
2006 }
2007 }
2008
2009 // Save the new version
2010 try {
2011 // FileWriter fw = new FileWriter(file);
2012
2013 // Open an Output Stream Writer to set encoding
2014 OutputStream fout = new FileOutputStream(file);
2015 OutputStream bout = new BufferedOutputStream(fout);
2016 Writer fw = new OutputStreamWriter(bout, "UTF-8");
2017
2018 String nextLine = null;
2019 while ((nextLine = packetContents.readLine()) != null) {
2020 fw.write(nextLine + '\n');
2021 }
2022 fw.flush();
2023 fw.close();
2024 MessageBay.displayMessage("Saved remote frame: " + frameName);
2025 } catch (IOException e) {
2026 MessageBay.errorMessage("Error remote saving " + frameName + ": "
2027 + e.getMessage());
2028 e.printStackTrace();
2029 }
2030 }
2031
2032 public static void setSavedProperties(Frame toSave) {
2033 toSave.setLastModifyDate(Formatter.getDateTime(), System.currentTimeMillis());
2034 toSave.setLastModifyUser(UserSettings.UserName.get());
2035 toSave.setVersion(toSave.getVersion() + 1);
2036 Time darkTime = new Time(SessionStats.getFrameDarkTime().getTime()
2037 + toSave.getDarkTime().getTime());
2038 Time activeTime = new Time(SessionStats.getFrameActiveTime().getTime()
2039 + toSave.getActiveTime().getTime());
2040 toSave.setDarkTime(darkTime);
2041 toSave.setActiveTime(activeTime);
2042 }
2043
2044 public static Path setupPersonalResources(String username) {
2045 Path personalResources = Paths.get(FrameIO.PARENT_FOLDER).resolve("resources-" + username);
2046 personalResources.toFile().mkdir();
2047 File[] globalResourcesToCopy = Paths.get(FrameIO.RESOURCES_PRIVATE_PATH).toFile().listFiles();
2048
2049 try {
2050 for (File toCopy: globalResourcesToCopy) {
2051 Path p = Paths.get(toCopy.getAbsolutePath());
2052 if (!p.getFileName().toString().equals(".res") && !p.getFileName().toString().equals("about")) {
2053 moveFileTree(p.toAbsolutePath(), personalResources.resolve(p.getFileName()));
2054 }
2055 }
2056 } catch (IOException e) {
2057 e.printStackTrace();
2058 personalResources = null;
2059 }
2060
2061 return personalResources;
2062 }
2063
2064 public static void migrateFrame(Frame toMigrate, Path destinationDirectory) {
2065 Path source = Paths.get(toMigrate.getFramePathReal());
2066 String destination = source.relativize(destinationDirectory).toString().substring(3).replace(File.separator, "/");
2067 try {
2068 Files.move(source, destinationDirectory);
2069 } catch (IOException e) {
2070 System.err.println("FrameIO::migrateFrame: failed to migrate from to new location. Message: " + e.getMessage());
2071 return;
2072 }
2073 try {
2074 FileWriter out = new FileWriter(source.toFile());
2075 out.write("REDIRECT:" + destination);
2076 out.flush();
2077 out.close();
2078 } catch (IOException e) {
2079 System.err.println("FrameIO::migrateFrame: failed to update file [" + source + "] to redirect to [" + destination + "] following migration. Message: " + e.getMessage());
2080 }
2081 }
2082
2083 private static void moveFileTree(Path source, Path target) throws IOException {
2084 if (source.toFile().isDirectory()) {
2085 if (!target.toFile().exists()) {
2086 Files.copy(source, target);
2087 }
2088 File[] files = source.toFile().listFiles();
2089 for (File file: files) {
2090 Path asPath = Paths.get(file.getAbsolutePath());
2091 moveFileTree(asPath, target.resolve(asPath.getFileName()));
2092 }
2093 } else {
2094 Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
2095 }
2096 }
2097}
Note: See TracBrowser for help on using the repository browser.