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