summaryrefslogtreecommitdiffstats
path: root/logo/src/xlogo/storage/global/GlobalConfig.java
blob: 1c5a27d2f2ebf4b350ccc3ee914d436450d03c56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
/*
 * XLogo4Schools - A Logo Interpreter specialized for use in schools, based on XLogo by Loic Le Coq
 * Copyright (C) 2013 Marko Zivkovic
 * Contact Information: marko88zivkovic at gmail dot com
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version. This program is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details. You should have received a copy of the
 * GNU General Public License along with this program; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * This Java source code belongs to XLogo4Schools, written by Marko Zivkovic
 * during his Bachelor thesis at the computer science department of ETH Zurich,
 * in the year 2013 and/or during future work.
 * It is a reengineered version of XLogo written by Loic Le Coq, published
 * under the GPL License at http://xlogo.tuxfamily.org/
 * Contents of this file were entirely written by Marko Zivkovic
 */

package xlogo.storage.global;

import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import xlogo.AppSettings;
import xlogo.interfaces.Observable;
import xlogo.interfaces.PropertyChangePublisher;
import xlogo.storage.StorableObject;
import xlogo.storage.workspace.WorkspaceConfig;
import xlogo.storage.workspace.WorkspaceConfig.WorkspaceProperty;

/**
 * This Config is stored in default location : "user.home". It contains information about the currently used workspaces on the computer
 * @author Marko Zivkovic
 */
public class GlobalConfig implements Serializable, Observable<GlobalConfig.GlobalProperty> {
	
	private static final long	serialVersionUID	= 2787615728665011813L;
	private static Logger		logger				= LogManager.getLogger(GlobalConfig.class.getSimpleName());
	
	public static final File DEFAULT_LOCATION = new File(System.getProperty("user.home"));

	public static boolean		DEBUG				= true;		// TODO set false
	public static final String	LOGO_FILE_EXTENSION	= ".lgo";
																												
	/**
	 * Creates the global config at default location, together with a virtual workspace
	 */
	public GlobalConfig() {
		workspaces = new TreeMap<String, String>();
	}
		
	public void cleanUpWorkspaces() {
		logger.trace("Cleaning up workspaces.");
		Map<String, String> existingWorkspaces = new TreeMap<String, String>();
		Map<String, String> lostWorkspaces = new TreeMap<String, String>();
		for (Entry<String, String> e : workspaces.entrySet()) {
			File file = new File(e.getValue());
			if (file.exists()) {
				logger.trace("\tConfirmed existence: " + e.getKey() + " at " + e.getValue());
				existingWorkspaces.put(e.getKey(), e.getValue());
			}
			else {
				logger.trace("\tLost workspace: " + e.getKey() + " at " + e.getValue());
				if (e.getKey().equals(lastUsedWorkspace)) {
					lastUsedWorkspace = null;
					currentWorkspace = null;
				}
				lostWorkspaces.put(e.getKey(), e.getValue());
			}
		}
		
		/*// TODO maybe reintroduce this warning. but currently ==> recursive singleton instantiation :-(
		if (lostWorkspaces.size() > 0) {
			StringBuilder msg = new StringBuilder();
			String message = AppSettings.getInstance().translate("message.some.workspaces.not.found");
			String at = AppSettings.getInstance().translate("word.at.filesystem.location");
			msg.append(message);
			for (Entry<String, String> e : lostWorkspaces.entrySet()) {
				msg.append('\t').append(e.getKey()).append(' ').append(at).append(' ').append(e.getValue())
						.append('\n');
			}
			DialogMessenger.getInstance().dispatchMessage(msg.toString());
		}*/
		workspaces = existingWorkspaces;
	}
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Physical Workspaces (stored on file system)
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
		
	/**
	 * Load the specified workspace from the file system.
	 * @param workspaceName
	 * @return the specified workspace or null if it does not exist.
	 * @throws IOException
	 */
	private StorableObject<WorkspaceConfig, WorkspaceProperty> retrieveWorkspace(String workspaceName) throws IOException {
		StorableObject<WorkspaceConfig, WorkspaceProperty> wsc = getCachedWorkspace(workspaceName);
		if (wsc != null) {
			logger.trace("Retrieved cached workspace: " + workspaceName);
			return wsc;
		}
		
		if (!existsWorkspace(workspaceName)) {
			logger.warn("Attempting to load an inexistent workspace: " + workspaceName);
			return null;
		}
		
		File wsDir = getWorkspaceDirectory(workspaceName);

		logger.trace("Retrieving workspace: " + workspaceName + " from " + wsDir.toString());
		try {
			wsc = new StorableObject<>(WorkspaceConfig.class, wsDir).createOrLoad();
			wsc.get().setDirectory(wsDir);
			cacheWorkspace(workspaceName, wsc);
		}
		catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | SecurityException ignore) { }
			
		return wsc;
	}
		
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Workspace Cache
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	/**
	 * Workspace Objects that have already been created or loaded from disk.
	 */
	private transient Map<String, StorableObject<WorkspaceConfig, WorkspaceProperty>>	cachedWorkspaces;
	
	private StorableObject<WorkspaceConfig, WorkspaceProperty> getCachedWorkspace(String workspaceName) {
		if (cachedWorkspaces == null) {
			cachedWorkspaces = new TreeMap<>();
		}
		return cachedWorkspaces.get(workspaceName);
	}
	
	private void cacheWorkspace(String workspaceName, StorableObject<WorkspaceConfig, WorkspaceProperty> wsc) {
		if (cachedWorkspaces == null) {
			cachedWorkspaces = new TreeMap<>();
		}
		cachedWorkspaces.put(workspaceName, wsc);
	}
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Workspaces
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	/**
	 * Logical Workspaces (name and location stored in Map)
	 */
	private Map<String, String>	workspaces;
	
	/**
	 * @param workspaceName
	 * @param location where the workspace is located: location/workspaceName/
	 */
	public void addWorkspace(String workspaceName, String location) {
		logger.trace("Adding workspace: '" + workspaceName + "' at " + location);
		workspaces.put(workspaceName, location);
		publisher.publishEvent(GlobalProperty.WORKSPACES);
		setLastUsedWorkspace(workspaceName);
	}
	
	public void addWorkspace(StorableObject<WorkspaceConfig, WorkspaceProperty> wc) {
		File location = wc.getLocation();
		String name = wc.get().getWorkspaceName();
		cacheWorkspace(name, wc);
		addWorkspace(name, location.getParentFile().toString());
	}
	
	public void removeWorkspace(String workspaceName) {
		logger.trace("Removing workspace: " + workspaceName);
		
		if (currentWorkspace != null && currentWorkspace.get().getWorkspaceName().equals(workspaceName)){
			leaveWorkspace();
		}
		
		if (lastUsedWorkspace.equals(workspaceName)) {
			lastUsedWorkspace = null;
			publisher.publishEvent(GlobalProperty.LAST_USED_WORKSPACE);
		}
		
		workspaces.remove(workspaceName);
		cachedWorkspaces.remove(workspaceName);
		publisher.publishEvent(GlobalProperty.WORKSPACES);
	}
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Workspace File Utility
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	/**
	 * @param wsName
	 * @return the parent directory of the workspace directory, or null if the workspace does not exist
	 */
	public File getWorkspaceLocation(String wsName) {
		String location = workspaces.get(wsName);
		if (location == null)
			return null;
		return new File(location);
	}
	
	/**
	 * @param wsName
	 * @return The workspace Directory that contains a physical representation of {@link WorkspaceConfig}
	 */
	public File getWorkspaceDirectory(String wsName) {
		File wsLocation = getWorkspaceLocation(wsName);
		if (wsLocation == null)
			return null;
		return new File(wsLocation.toString() + File.separator + wsName);
	}
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Workspaces
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	/**
	 * @return the names of all existing workspaces
	 */
	public String[] getAllWorkspaces() {
		return (String[]) workspaces.keySet().toArray(new String[workspaces.size()]);
	}
	
	/**
	 * A workspace exists logically, if its location is known by the GlobalConfig.
	 * @param workspace
	 * @return
	 */
	public boolean existsWorkspace(String workspace) {
		return workspaces.get(workspace) != null;
	}
		
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Last used workspace
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	private String	lastUsedWorkspace;
	
	public String getLastUsedWorkspace() {
		return lastUsedWorkspace;
	}
	
	/**
	 * Succeeds if the workspace exists
	 * @param workspace
	 */
	private void setLastUsedWorkspace(String workspace) {
		if (existsWorkspace(workspace)) {
			lastUsedWorkspace = workspace;
			publisher.publishEvent(GlobalProperty.LAST_USED_WORKSPACE);
		}
	}
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Current Workspace
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	private transient StorableObject<WorkspaceConfig, WorkspaceProperty>	currentWorkspace;
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Entering and Leaving Workspaces
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	public StorableObject<WorkspaceConfig, WorkspaceProperty> getCurrentWorkspace() {
		return currentWorkspace;
	}
	

	
	/**
	 * Load the workspace
	 * <p>Always succeeds if workspaceName equals {@link WorkspaceConfig#VIRTUAL_WORKSPACE}
	 * @param workspaceName - the workspace to load and enter
	 * @throws IOException - if the workspace could not be loaded
	 */
	public void enterWorkspace(String workspaceName) throws IOException {
		logger.trace("Entering workspace: " + workspaceName);
		if (currentWorkspace != null) {
			leaveWorkspace();
		}
		currentWorkspace = retrieveWorkspace(workspaceName);
		
		setLastUsedWorkspace(workspaceName);
		
		publisher.publishEvent(GlobalProperty.CURRENT_WORKSPACE);
		
		currentWorkspace.get().enterInitialUserSpace();
	}
	
	/**
	 * Afterwards, currentWorkspace is null
	 * @throws IOException If workspace could not be saved.
	 */
	public void leaveWorkspace() {
		if (currentWorkspace == null)
			throw new IllegalStateException(AppSettings.getInstance()
					.translate("error.leaving.ws.without.being.in.one"));
		logger.trace("Leaving workspace: " + currentWorkspace.get().getWorkspaceName());
		
		if (currentWorkspace.get().getActiveUser() != null) {
			try {
				currentWorkspace.get().leaveUserSpace();
			}
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if (currentWorkspace.isDirty())
			currentWorkspace.store();
		
		currentWorkspace = null;

		publisher.publishEvent(GlobalProperty.CURRENT_WORKSPACE);
	}
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Password protection
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	/**
	 * if null, no password is requested
	 */
	private byte[]	masterPassword	= null;
	
	/**
	 * Need old password to authenticate
	 * @param oldPw initially null
	 * @param newPw
	 * @return success
	 */
	public boolean setNewPassword(String oldPw, String newPw) {
		if (masterPassword == null || authenticate(oldPw)) {
			if (newPw == null)
				masterPassword = null;
			else
				masterPassword = hash(newPw);
			publisher.publishEvent(GlobalProperty.PASSWORD);
			return true;
		}
		else {
			return false;
		}
	}
	
	public boolean isPasswordRequired() {
		return masterPassword != null;
	}
	
	public boolean authenticate(String password) {
		if (masterPassword == null)
			return true;
		String entered = null;
		if (password != null)
			entered = new String(hash(password));
		String master = new String(masterPassword);
		boolean auth = master.equals(entered);
		return auth;
	}
	
	/**
	 * Hashing the password with MD5 is enough for this application. We just don't want to store readable plain text.
	 * Note that MD5 is generally considered insecure for security critical applications.
	 * @param text
	 * @return hashed bytes
	 */
	private byte[] hash(String text) {
		if (text == null)
			return null;
		
		byte[] bytesOfMessage;
		try {
			bytesOfMessage = text.getBytes("UTF-8");
		}
		catch (UnsupportedEncodingException e1) {
			bytesOfMessage = text.getBytes();	// this should not happen anyway
		}
		
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			return md.digest(bytesOfMessage);
		}
		catch (NoSuchAlgorithmException e) {
			return bytesOfMessage;	// this should not happen anyway
		}
	}
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Path variable
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	/**
	 * Path to the current directory for the Logo environment
	 */
	private ArrayList<String>	path	= new ArrayList<String>();
	
	public ArrayList<String> getPath() {
		return path;
	}
	
	public void setPath(ArrayList<String> path) {
		this.path = path;
		publisher.publishEvent(GlobalProperty.PATH);
	}
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Application Meta Data
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	/**
	 * This is not really used. Artifact from the past.
	 * @return
	 */
	public static String getVersion() {
		return "XLogo4Schools 0.0.1";
	}
	
	/* *
	 * Note : should be equal as in {@link Lanceur}
	 */
	//private static String	PROPERTIES_PREFIX		= "ch.ethz.abz.xlogo4schools";
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * JRE Memory allocation parameters
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	/**
	 * Note : should be equal as in {@link Lanceur}
	 */
	private static int	DEFAULT_MEMORY_ALLOC	= 128;
	
	private static int	maximumMemory;
	
	/**
	 * The Maximum amount of memory that this application is allowed to consume by the JVM
	 * @return
	 */
	public static int getMaximumMemory() {
		if (maximumMemory < 64) {
			// This doesn't work as expected :-(
			//Preferences prefs = Preferences.systemRoot().node(PROPERTIES_PREFIX);
			//maximumMemory = prefs.getInt("appMemory", DEFAULT_MEMORY_ALLOC);
			maximumMemory = DEFAULT_MEMORY_ALLOC;
		}
		return maximumMemory;
	}
	
	private transient int	maxMemoryAtNextStart	= getMaximumMemory();
	
	/**
	 * @return The amount of memory in MB that Lanceur will cause JVM to allocate to XLogo4Schools the next time this application is started.
	 */
	public int getMaxMemoryAtNextStart() {
		if (maxMemoryAtNextStart < 64)
			maxMemoryAtNextStart = getMaximumMemory();
		return maxMemoryAtNextStart;
	}
	
	/**
	 * @see #getMaxMemoryAtNextStart()
	 * cannot set this below 64MB
	 * @param maxMemory
	 */
	public void setMaxMemoryAtNextStart(int maxMemory) {
		if (maxMemory < 64)
			return;
		// This doesn't work as well :-(
		//Preferences prefs = Preferences.systemRoot().node(PROPERTIES_PREFIX);
		//prefs.putInt("appMemory", maxMemory);
	}
	
	/**
	 * The amount of memory that the memory checker allows the application to consume.
	 * It's 0.9*{@link #getMaximumMemory()}} in bytes.
	 */
	public static long getMemoryThreshold() {
		return (long) (0.9 * ((long) GlobalConfig.getMaximumMemory() * 1024L * 1024L));
	}
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Fonts
	 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	public static final Font[]	fonts	= GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();	// Toolkit.getDefaultToolkit().getFontList();
																											
	static public int getFontId(Font font) {
		for (int i = 0; i < fonts.length; i++) {
			if (fonts[i].getFontName().equals(font.getFontName()))
				return i;
		}
		return 0;
	}
	
	/* * * * * * *
	 * Event Handling : Property Change Listeners
	 * * * * * * */
						
	public enum GlobalProperty {
		PATH, PASSWORD, LAST_USED_WORKSPACE, CURRENT_WORKSPACE, WORKSPACES;
	}

	private transient PropertyChangePublisher<GlobalProperty> publisher = new PropertyChangePublisher<>();
	
	@Override
	public void addPropertyChangeListener(GlobalProperty property, PropertyChangeListener listener) {
		if (publisher == null){
			publisher = new PropertyChangePublisher<>();
		}
		publisher.addPropertyChangeListener(property, listener);
	}
	
	@Override
	public void removePropertyChangeListener(GlobalProperty property, PropertyChangeListener listener) {
		publisher.removePropertyChangeListener(property, listener);
	}
}