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