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