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

Last change on this file since 1474 was 1474, checked in by bnemhaus, 5 years ago

Added FrameIO.Mail to the default paths populated on profile frames. With more time this could be done better; as per comment in UserSettings::appendDefaultFolders

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