Révision 3000

tmp/org.txm.core/src/java/org/txm/xml/XMLProcessor.java (revision 3000)
2 2

  
3 3
import java.io.BufferedOutputStream;
4 4
import java.io.File;
5
import java.io.FileNotFoundException;
6 5
import java.io.FileOutputStream;
7 6
import java.io.IOException;
8 7
import java.net.URL;
......
34 33
	/**
35 34
	 * list of XML elements that are always milestones elements
36 35
	 */
37
	protected HashSet<String> milestoneElements = new HashSet<String>();
36
	protected HashSet<String> milestoneElements = new HashSet<>();
38 37
	
39 38
	/**
40 39
	 * 
......
71 70
			return parser.getAttributeValue(null, name);
72 71
		}
73 72
		
74
		//no luck try all attributes 
73
		// no luck try all attributes
75 74
		int c = parser.getAttributeCount();
76 75
		for (int i = 0; i < c; i++) {
77 76
			if (name.equals(parser.getAttributeLocalName(i))) {
......
95 94
	protected void after(boolean allWentWell) throws XMLStreamException, IOException {
96 95
		
97 96
		super.after(allWentWell); // close parser, inputData and factory
98
				
97
		
99 98
		if (writer != null) writer.close();
100 99
		
101 100
		if (output != null) output.close();
......
106 105
	 *
107 106
	 * @param outfile the outfile
108 107
	 * @return true, if successful
109
	 * @throws XMLStreamException 
110
	 * @throws IOException 
108
	 * @throws XMLStreamException
109
	 * @throws IOException
111 110
	 */
112 111
	private boolean createOutput(File f) throws XMLStreamException, IOException {
113
			if (writer != null) { // process from a file
114
				writer.close();
115
			}
116
			if (output != null) { // process from a file
117
				output.close();
118
			}
119
			
120
			output = new BufferedOutputStream(new FileOutputStream(f), 16 * 1024);
121
			
122
			writer = outfactory.createXMLStreamWriter(output, "UTF-8");// create a new file
123
			writer.setNamespaceContext(Nscontext);
124
			return true;
112
		if (writer != null) { // process from a file
113
			writer.close();
114
		}
115
		if (output != null) { // process from a file
116
			output.close();
117
		}
118
		
119
		output = new BufferedOutputStream(new FileOutputStream(f), 16 * 1024);
120
		
121
		// create writer later
122
		return true;
125 123
	}
126 124
	
127 125
	public boolean process(File outFile) throws XMLStreamException, IOException {
......
167 165
				switch (event) {
168 166
					case XMLStreamConstants.START_DOCUMENT:
169 167
						processStartDocument();
170
					break;
168
						break;
171 169
					case XMLStreamConstants.SPACE:
172 170
						processSpace();
173
					break;
171
						break;
174 172
					case XMLStreamConstants.NOTATION_DECLARATION:
175 173
						processNotationDeclaration();
176
					break;
174
						break;
177 175
					case XMLStreamConstants.NAMESPACE:
178 176
						processNamespace();
179 177
						break;
......
232 230
		return true;
233 231
	}
234 232
	
233
	@Override
235 234
	protected void processStartDocument() throws XMLStreamException {
236
		writer.writeStartDocument(parser.getCharacterEncodingScheme(), parser.getVersion());
235
		
236
		String encoding = parser.getCharacterEncodingScheme();
237
		if (encoding == null) {
238
			encoding = "UTF-8";
239
		}
240
		writer = outfactory.createXMLStreamWriter(output, encoding);// create a new file
241
		writer.setNamespaceContext(Nscontext);
242
		
243
		writer.writeStartDocument(encoding, parser.getVersion());
237 244
		writer.writeCharacters("\n");
238 245
	}
239

  
246
	
240 247
	@Override
241 248
	protected void processNamespace() throws XMLStreamException {
242 249
		this.Nscontext.addNamespace(parser.getPrefix(), parser.getNamespaceURI());
......
250 257
		if (prefix != null && prefix.length() > 0) {
251 258
			if (milestoneElements.contains(localname)) {
252 259
				writer.writeEmptyElement(Nscontext.getNamespaceURI(prefix), localname);
253
			} else {
260
			}
261
			else {
254 262
				writer.writeStartElement(Nscontext.getNamespaceURI(prefix), localname);
255 263
			}
256 264
		}
257 265
		else {
258 266
			if (milestoneElements.contains(localname)) {
259 267
				writer.writeEmptyElement(localname);
260
			} else {
268
			}
269
			else {
261 270
				writer.writeStartElement(localname);
262 271
			}
263 272
		}
......
366 375
			// parentParser.writer.writeAttribute("hook", name);
367 376
			// }
368 377
			// };
369
//			XPathHookActivator xpathActivator = new XPathHookActivator(null, "//p");
370
//			XPathsHookActivator xpathsActivator = new XPathsHookActivator(null, Arrays.asList("//p", "//p"));
371
//			IdentityHook hook2 = new IdentityHook("hook2", xpathsActivator, builder) {
372
//				
373
//				@Override
374
//				public boolean _activate() {
375
//					System.out.println("ACTIVATING " + name + " AT " + getLocation());
376
//					return true;
377
//				}
378
//				
379
//				@Override
380
//				public boolean deactivate() {
381
//					System.out.println("DEACTIVATING " + name + " AT " + getLocation());
382
//					return true;
383
//				}
384
//				
385
//				@Override
386
//				public void processStartElement() throws XMLStreamException, IOException {
387
//					super.processStartElement();
388
//					parentParser.writer.writeAttribute("hook", name);
389
//				}
390
//			};
391
//			
392
//			// DOMIdentityHook hook3 = new DOMIdentityHook("hook3", xpathsActivator, builder) {
378
			// XPathHookActivator xpathActivator = new XPathHookActivator(null, "//p");
379
			// XPathsHookActivator xpathsActivator = new XPathsHookActivator(null, Arrays.asList("//p", "//p"));
380
			// IdentityHook hook2 = new IdentityHook("hook2", xpathsActivator, builder) {
393 381
			//
382
			// @Override
383
			// public boolean _activate() {
384
			// System.out.println("ACTIVATING " + name + " AT " + getLocation());
385
			// return true;
386
			// }
387
			//
388
			// @Override
389
			// public boolean deactivate() {
390
			// System.out.println("DEACTIVATING " + name + " AT " + getLocation());
391
			// return true;
392
			// }
393
			//
394
			// @Override
395
			// public void processStartElement() throws XMLStreamException, IOException {
396
			// super.processStartElement();
397
			// parentParser.writer.writeAttribute("hook", name);
398
			// }
394 399
			// };
400
			//
401
			// // DOMIdentityHook hook3 = new DOMIdentityHook("hook3", xpathsActivator, builder) {
402
			//
403
			// };
395 404
			
396 405
			long time = System.currentTimeMillis();
397 406
			if (builder.process(output)) {
398 407
				System.out.println("Time=" + (System.currentTimeMillis() - time));
399
				//System.out.println("XPaths activator has done working ? " + xpathsActivator.hasAllXpathsBeenProcessed());
408
				// System.out.println("XPaths activator has done working ? " + xpathsActivator.hasAllXpathsBeenProcessed());
400 409
			}
401 410
			else {
402 411
				System.out.println("failure !");
......
419 428
			milestoneElements.remove(e);
420 429
		}
421 430
	}
422

  
431
	
423 432
	/**
424 433
	 * 
425 434
	 * @return the actual hooks hash
tmp/org.txm.core/src/java/org/txm/Toolbox.java (revision 3000)
81 81
 * 
82 82
 */
83 83
public class Toolbox {
84

  
84
	
85 85
	public static final DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
86
	//public static final DateFormat shortUKDateformat = new SimpleDateFormat("dd-MM-yy");
87

  
88
	private static LinkedHashMap<EngineType, EnginesManager<?>> enginesManagers = new LinkedHashMap<EngineType, EnginesManager<?>>();
89

  
86
	// public static final DateFormat shortUKDateformat = new SimpleDateFormat("dd-MM-yy");
87
	
88
	private static LinkedHashMap<EngineType, EnginesManager<?>> enginesManagers = new LinkedHashMap<>();
89
	
90 90
	private static boolean initializing = false;
91

  
91
	
92 92
	/** The state. */
93 93
	private static boolean state = false;
94

  
94
	
95 95
	/** Root of all TXMResults and manages the corpus */
96 96
	public static Workspace workspace;
97

  
97
	
98 98
	/**
99 99
	 * 
100 100
	 * @param enginesManager
......
102 102
	private static void addEngineManager(EnginesManager<?> enginesManager) {
103 103
		enginesManagers.put(enginesManager.getEnginesType(), enginesManager);
104 104
	}
105

  
105
	
106 106
	/**
107 107
	 * If search engine or stats engine or workspace is not ready then the toolbox is not ready.
108 108
	 *
......
111 111
	private static boolean checkState() {
112 112
		return state;
113 113
	}
114

  
114
	
115 115
	private static boolean fetchEnginesManagers() {
116 116
		Log.finest("Fetching engines managers...");
117 117
		enginesManagers.clear();
118
		//System.out.println("Contributions of "+EnginesManager.ENGINEMANAGER_EXTENSION_POINT_ID);
119
		//Platform.getExtensionRegistry().getExtensionPoints();
118
		// System.out.println("Contributions of "+EnginesManager.ENGINEMANAGER_EXTENSION_POINT_ID);
119
		// Platform.getExtensionRegistry().getExtensionPoints();
120 120
		IConfigurationElement[] contributions = RegistryFactory.getRegistry().getConfigurationElementsFor(EnginesManager.ENGINES_MANAGER_EXTENSION_POINT_ID);
121
		//System.out.println("contributions: "+Arrays.toString(contributions));
122

  
121
		// System.out.println("contributions: "+Arrays.toString(contributions));
122
		
123 123
		Log.fine(contributions.length + " engines managers found.");
124

  
124
		
125 125
		for (int i = 0; i < contributions.length; i++) {
126 126
			try {
127
				EnginesManager<?> enginesManager = (EnginesManager<?>)contributions[i].createExecutableExtension("class"); //$NON-NLS-1$
128

  
127
				EnginesManager<?> enginesManager = (EnginesManager<?>) contributions[i].createExecutableExtension("class"); //$NON-NLS-1$
128
				
129 129
				Log.fine("Registering " + enginesManager.getEnginesDescription() + " engines manager...");
130 130
				addEngineManager(enginesManager);
131 131
				if (enginesManager.fetchEngines()) {
132
					//System.out.println("add engine: "+engine);
133

  
132
					// System.out.println("add engine: "+engine);
133
					
134 134
				}
135 135
				else {
136 136
					Log.warning("No engine found for " + enginesManager + ", installation failed.");
137 137
				}
138
			} catch(Throwable e) {
138
			}
139
			catch (Throwable e) {
139 140
				e.printStackTrace();
140
			} 
141
			}
141 142
		}
142

  
143
		
143 144
		return true;
144 145
	}
145

  
146
	
146 147
	/**
147 148
	 * Gets a preference from the Toolbox Preferences node.
148 149
	 * 
......
152 153
	public static String getPreference(String key) {
153 154
		return TBXPreferences.getInstance().getString(key);
154 155
	}
155

  
156
	
156 157
	/**
157 158
	 * Sets a preference of the Toolbox Preferences node.
159
	 * 
158 160
	 * @param key
159 161
	 * @param value
160 162
	 */
161 163
	public static void setPreference(String key, Object value) {
162 164
		TBXPreferences.getInstance().put(key, value);
163 165
	}
164

  
166
	
165 167
	/**
166 168
	 * Gets the manager of the specified engine type.
169
	 * 
167 170
	 * @param engineType
168 171
	 * @return
169 172
	 */
170 173
	public static EnginesManager<? extends Engine> getEngineManager(EngineType engineType) {
171

  
174
		
172 175
		if (enginesManagers == null) {
173 176
			return null;
174 177
		}
175 178
		return enginesManagers.get(engineType);
176 179
	}
177

  
180
	
178 181
	/**
179 182
	 * Gets the TXM working directory.
180
	 * @return the TXM working directory set with the USER_TXM_HOME preference key 
183
	 * 
184
	 * @return the TXM working directory set with the USER_TXM_HOME preference key
181 185
	 */
182 186
	public static String getTxmHomePath() {
183 187
		return getPreference(TBXPreferences.USER_TXM_HOME);
184 188
	}
185

  
189
	
186 190
	/**
187 191
	 * Initializes the Toolbox with the parameters read in the file
188 192
	 * textometrie.properties found in the user home directory
......
200 204
		File configFile = new File(txmDirectory, "textometrie.properties"); //$NON-NLS-1$
201 205
		if (!configFile.exists()) {
202 206
			initializing = false;
203
			throw new IllegalArgumentException(TXMCoreMessages.file 
207
			throw new IllegalArgumentException(TXMCoreMessages.file
204 208
					+ configFile.getAbsolutePath()
205
					+ TXMCoreMessages.doesNotExists); 
209
					+ TXMCoreMessages.doesNotExists);
206 210
		}
207

  
211
		
208 212
		boolean ret = initialize(configFile);
209 213
		initializing = false;
210 214
		return ret;
211 215
	}
212

  
216
	
213 217
	/**
214 218
	 * 
215 219
	 * @param preferencesStore
......
219 223
	public static boolean initialize(Class preferencesStore) throws Exception {
220 224
		return initialize(preferencesStore, new LogMonitor("initializing Toolbox"));
221 225
	}
222

  
226
	
223 227
	/**
224 228
	 * Initializes the Toolbox using the INSTANCE SCOPE preferences of TXMPreferences
225 229
	 *
226 230
	 * @param props the props
227 231
	 * @param monitor the optional monitor
228 232
	 * @return true, if successful
229
	 * @throws Exception 
233
	 * @throws Exception
230 234
	 */
231 235
	public static boolean initialize(Class preferencesStore, IProgressMonitor monitor) throws Exception {
232 236
		initializing = true;
233

  
237
		
234 238
		try {
235 239
			Log.fine("Initializing logger...");
236 240
			Log.setLevel(Level.parse(getPreference(TBXPreferences.LOG_LEVEL)));
237 241
			Log.setPrintInConsole(TBXPreferences.getInstance().getBoolean(TBXPreferences.ADD_TECH_LOGS));
238 242
			Log.log_stacktrace_boolean = TBXPreferences.getInstance().getBoolean(TBXPreferences.LOG_STACKTRACE);
239

  
243
			
240 244
			if (!getPreference(TBXPreferences.LOG_DIR).isEmpty()) {
241 245
				Log.setPrintInFile(TBXPreferences.getInstance().getBoolean(TBXPreferences.LOG_IN_FILE), new File(getPreference(TBXPreferences.LOG_DIR)));
242
			} else {
246
			}
247
			else {
243 248
				Log.setPrintInFile(TBXPreferences.getInstance().getBoolean(TBXPreferences.LOG_IN_FILE));
244 249
			}
245
		} catch(Exception e) {
246
			System.out.println("Error while initializing logger: "+e);
250
		}
251
		catch (Exception e) {
252
			System.out.println("Error while initializing logger: " + e);
247 253
			e.printStackTrace();
248 254
		}
249

  
255
		
250 256
		if (monitor != null) {
251 257
			monitor.setTaskName(TXMCoreMessages.initializingToolbox);
252 258
		}
......
255 261
				monitor.subTask(TXMCoreMessages.loadingExtensionPreInstallation);
256 262
			}
257 263
			pluginsPreinstallation(monitor);
258
		} catch(Exception e) {
264
		}
265
		catch (Exception e) {
259 266
			Log.warning(NLS.bind(TXMCoreMessages.errorWhilePreInstallingPluginsP0, e.getLocalizedMessage()));
260 267
		}
261

  
268
		
262 269
		if (monitor != null && monitor.isCanceled()) return false;
263

  
270
		
264 271
		try {
265 272
			// initialize workspace : list of corpus loaded in TXM
266 273
			// copy shared files if needed
267 274
			state = startWorkspace(monitor);
268 275
			if (monitor != null && monitor.isCanceled()) return false;
269

  
270

  
271

  
272
		} catch (Exception e) {
276
			
277
			
278
			
279
		}
280
		catch (Exception e) {
273 281
			initializing = false;
274 282
			throw e;
275 283
		}
276

  
284
		
277 285
		try {
278 286
			startEnginesManagers(monitor);
279 287
			if (monitor != null && monitor.isCanceled()) return false;
280
		} catch (Exception e) {
288
		}
289
		catch (Exception e) {
281 290
			Log.warning("Error while starting engines.");
282 291
			e.printStackTrace();
283 292
			initializing = false;
284 293
			throw e;
285 294
		}
286

  
295
		
287 296
		Log.finest(TXMCoreMessages.bind(TXMCoreMessages.ToolboxStatesWorkspaceColonP0, state));
288

  
297
		
289 298
		try {
290 299
			if (monitor != null) {
291 300
				monitor.subTask(TXMCoreMessages.loadingExtensionPostInstallation);
292

  
293 301
			}
294 302
			pluginsPostinstallation(monitor);
295 303
			if (monitor != null && monitor.isCanceled()) return false;
296
		} catch(Exception e) {
304
		}
305
		catch (Exception e) {
297 306
			Log.warning(NLS.bind(TXMCoreMessages.errorWhilePostInstallingPluginsP0, e.getLocalizedMessage()));
298 307
		}
299

  
308
		
300 309
		// loads and recreate the existing projects, loadParameters() needs engines to be ready
301 310
		if (workspace != null) {
302 311
			workspace.loadProjectsFromProjectScopes(monitor);
303 312
			monitor.subTask("");
304
		} else {
313
		}
314
		else {
305 315
			System.out.println("Error: Toolbox not correctly initialized. Aborting workspace initialization.");
306 316
		}
307

  
317
		
308 318
		initializing = false;
309 319
		if (monitor != null) {
310 320
			monitor.setTaskName("");
311 321
		}
312 322
		return checkState();
313 323
	}
314

  
324
	
315 325
	/**
316 326
	 * initialize the toolbox from a UTF-8 file
317 327
	 * 
......
325 335
	public static boolean initialize(File file) throws Exception {
326 336
		initializing = true;
327 337
		String encoding = "UTF-8"; //$NON-NLS-1$
328

  
338
		
329 339
		// Windows OS
330 340
		if (OSDetector.isFamilyWindows()) {
331 341
			encoding = "ISO-8859-1"; //$NON-NLS-1$
332
		}		
333

  
342
		}
343
		
334 344
		boolean ret = initialize(file, encoding);
335 345
		initializing = false;
336 346
		return ret;
337 347
	}
338

  
348
	
339 349
	/**
340 350
	 * Initializes the toolbox with the parameters read in the properties file
341 351
	 * passed in argument.
......
348 358
	 */
349 359
	public static boolean initialize(File file, String encoding) throws Exception {
350 360
		initializing = true;
351

  
361
		
352 362
		try {
353 363
			BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
354 364
			String line = input.readLine();
......
356 366
				String[] split = line.split("="); //$NON-NLS-1$
357 367
				if (split.length == 2) {
358 368
					setPreference(split[0], split[1]);
359
				} else if (split.length > 2) {
369
				}
370
				else if (split.length > 2) {
360 371
					String[] subsplit = new String[split.length - 1];
361 372
					System.arraycopy(split, 1, subsplit, 0, split.length - 1);
362 373
					setPreference(split[0], StringUtils.join(subsplit, "="));
......
364 375
				line = input.readLine();
365 376
			}
366 377
			input.close();
367
		} catch (Exception e) {
378
		}
379
		catch (Exception e) {
368 380
			initializing = false;
369 381
			System.err.println(e);
370 382
			throw e;
371 383
		}
372 384
		return initialize(TBXPreferences.class);
373 385
	}
374

  
386
	
375 387
	/**
376 388
	 * test if searchEngine and statEngine and Workspace are initialized.
377 389
	 *
......
380 392
	public static boolean isInitialized() {
381 393
		return checkState();
382 394
	}
383

  
395
	
384 396
	public static boolean isInitializing() {
385 397
		return initializing;
386 398
	}
387

  
399
	
388 400
	/**
389 401
	 * Allow to install a TXM extension AFTER the Toolbox is initialized
390
	 * @param monitor 
402
	 * 
403
	 * @param monitor
391 404
	 */
392 405
	private static void pluginsPostinstallation(IProgressMonitor monitor) {
393

  
406
		
394 407
		IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(PostInstallationStep.EXTENSION_ID);
395

  
408
		
396 409
		Log.fine(TXMCoreMessages.loadingExtensions);
397 410
		Log.fine(Arrays.toString(config));
398

  
411
		
399 412
		for (IConfigurationElement e : config) {
400 413
			if (monitor != null && monitor.isCanceled()) return;
401 414
			try {
402 415
				Log.fine(NLS.bind(TXMCoreMessages.evaluatingExtensionColonP0FromP1, e.getName(), e.getContributor().getName()));
403

  
416
				
404 417
				final Object o = e.createExecutableExtension("class"); //$NON-NLS-1$
405 418
				if (o instanceof PostInstallationStep) {
406 419
					ISafeRunnable runnable = new ISafeRunnable() {
420
						
407 421
						@Override
408 422
						public void handleException(Throwable exception) {
409 423
							Log.severe(NLS.bind(TXMCoreMessages.exceptionColonP0, exception));
410 424
						}
411

  
425
						
412 426
						@Override
413 427
						public void run() throws Exception {
414 428
							((PostInstallationStep) o).install();
......
416 430
					};
417 431
					SafeRunner.run(runnable);
418 432
				}
419
			} catch (Exception ex) {
433
			}
434
			catch (Exception ex) {
420 435
				Log.severe("Exception while installing " + e.getName() + ".");
421 436
				ex.printStackTrace();
422 437
			}
423 438
		}
424 439
	}
425

  
440
	
426 441
	/**
427 442
	 * Allow to install a TXM extension BEFORE the Toolbox is initialized
428 443
	 */
429 444
	private static void pluginsPreinstallation(IProgressMonitor monitor) {
430

  
445
		
431 446
		IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(PostInstallationStep.EXTENSION_ID);
432 447
		Log.fine(TXMCoreMessages.loadingExtensions);
433 448
		Log.fine(Arrays.toString(config));
434

  
449
		
435 450
		for (IConfigurationElement e : config) {
436 451
			if (monitor != null && monitor.isCanceled()) return;
437 452
			try {
438 453
				Log.fine(NLS.bind(TXMCoreMessages.evaluatingExtensionColonP0FromP1, e.getName(), e.getContributor().getName()));
439

  
454
				
440 455
				final Object o = e.createExecutableExtension("class"); //$NON-NLS-1$
441 456
				if (o instanceof PostInstallationStep) {
442 457
					ISafeRunnable runnable = new ISafeRunnable() {
458
						
443 459
						@Override
444 460
						public void handleException(Throwable exception) {
445 461
							Log.severe(NLS.bind(TXMCoreMessages.exceptionColonP0, exception));
446 462
						}
447

  
463
						
448 464
						@Override
449 465
						public void run() throws Exception {
450 466
							((PostInstallationStep) o).preInstall();
......
452 468
					};
453 469
					SafeRunner.run(runnable);
454 470
				}
455
			} catch (Exception ex) {
471
			}
472
			catch (Exception ex) {
456 473
				Log.severe("Exception while installing " + e.getName() + ".");
457 474
				ex.printStackTrace();
458 475
			}
459 476
		}
460 477
	}
461

  
478
	
462 479
	/**
463 480
	 * Removes an engines manager.
481
	 * 
464 482
	 * @param enginesManager
465 483
	 */
466 484
	private static void removeEngineManager(EnginesManager<?> enginesManager) {
467 485
		enginesManagers.remove(enginesManager.getEnginesType());
468 486
		Log.finest("Engines manager removed: " + enginesManager);
469 487
	}
470

  
488
	
471 489
	/**
472 490
	 * Restarts the toolbox.
473 491
	 *
474 492
	 * @return true, if successful
475
	 * @throws Exception 
493
	 * @throws Exception
476 494
	 */
477 495
	public static boolean restart() throws Exception {
478 496
		Toolbox.shutdown();
479 497
		Toolbox.initialize(TBXPreferences.class);
480 498
		return checkState();
481 499
	}
482

  
483
	//	/**
484
	//	 * Restart the toolbox's workspace.
485
	//	 *
486
	//	 * @return true, if successful
487
	//	 */
488
	//	public static boolean restartWorkspace(IProgressMonitor monitor) {
489
	//		try {
490
	//			shutdownWorkspace();
491
	//			startWorkspace(monitor);
492
	//		} catch (Exception e) {
493
	//			Log.severe("Error while restarting workspace.");
494
	//			e.printStackTrace();
495
	//		}
496
	//		return checkState();
497
	//	}
498

  
500
	
501
	// /**
502
	// * Restart the toolbox's workspace.
503
	// *
504
	// * @return true, if successful
505
	// */
506
	// public static boolean restartWorkspace(IProgressMonitor monitor) {
507
	// try {
508
	// shutdownWorkspace();
509
	// startWorkspace(monitor);
510
	// } catch (Exception e) {
511
	// Log.severe("Error while restarting workspace.");
512
	// e.printStackTrace();
513
	// }
514
	// return checkState();
515
	// }
516
	
499 517
	/**
500 518
	 * Shut the toolbox down.
501 519
	 */
502 520
	public static void shutdown() {
503

  
521
		
504 522
		stopEnginesManagers();
505

  
523
		
506 524
		try {
507 525
			// FIXME: tmp solution before IProject: remove all not persistable result nodes
508
			//TXMPreferences.deleteAllNotPersistableResultsNodes();
526
			// TXMPreferences.deleteAllNotPersistableResultsNodes();
509 527
			// FIXME: tmp solution before IProject: remove result local nodes if persistence preference is disabled
510
			//			if (!TBXPreferences.getInstance().getBoolean(TBXPreferences.AUTO_PERSISTENCE_ENABLED)) {
511
			//				TXMPreferences.deleteAllResultsNodes();
512
			//			}
528
			// if (!TBXPreferences.getInstance().getBoolean(TBXPreferences.AUTO_PERSISTENCE_ENABLED)) {
529
			// TXMPreferences.deleteAllResultsNodes();
530
			// }
513 531
			// FIXME: other tmp solution
514
			//TODO iterates over opened projects to save them (not close); add this code to project.close
532
			// TODO iterates over opened projects to save them (not close); add this code to project.close
515 533
			
516

  
534
			
517 535
			// save projects parameters
518 536
			if (Toolbox.workspace != null) {
519 537
				TXMResult.deleteAllNonPersistentResults(Toolbox.workspace);
......
521 539
			}
522 540
			Toolbox.workspace = null;
523 541
			state = false;
524

  
525
			//save global preferences
542
			
543
			// save global preferences
526 544
			TXMPreferences.saveAll();
527
		} catch (Exception e) {
545
		}
546
		catch (Exception e) {
528 547
			// TODO Auto-generated catch block
529 548
			e.printStackTrace();
530 549
		}
531 550
	}
532

  
533
	//	/**
534
	//	 * Shut the toolbox workspace down.
535
	//	 */
536
	//	public static void shutdownWorkspace() {
537
	//		try {
538
	//			Toolbox.workspace.saveParameters();
539
	//			Toolbox.workspace = null;
540
	//			state = false;
541
	//		} catch (Exception e) {
542
	//			Log.severe("Error while closing workspace.");
543
	//			e.printStackTrace();
544
	//		}
545
	//	}
546

  
551
	
552
	// /**
553
	// * Shut the toolbox workspace down.
554
	// */
555
	// public static void shutdownWorkspace() {
556
	// try {
557
	// Toolbox.workspace.saveParameters();
558
	// Toolbox.workspace = null;
559
	// state = false;
560
	// } catch (Exception e) {
561
	// Log.severe("Error while closing workspace.");
562
	// e.printStackTrace();
563
	// }
564
	// }
565
	
547 566
	public static boolean startEnginesManagers(IProgressMonitor monitor) {
548

  
567
		
549 568
		fetchEnginesManagers();
550

  
569
		
551 570
		Log.finest("Starting engines of the " + enginesManagers.keySet().size() + " engines managers...");
552

  
571
		
553 572
		boolean result = true;
554 573
		for (EngineType et : enginesManagers.keySet()) {
555 574
			EnginesManager<?> enginesManager = enginesManagers.get(et);
556 575
			try {
557 576
				Log.finest(enginesManager.getClass().getSimpleName() + ": starting " + enginesManager.getEngines().size() + " " + enginesManager.getEnginesDescription() + " engine(s)...");
558 577
				result = enginesManager.startEngines(monitor) && result; // order is important
559
			} catch(Exception e) {
578
			}
579
			catch (Exception e) {
560 580
				Log.severe("Error while starting engines of the " + enginesManager.getEnginesDescription() + " engines manager.");
561 581
				e.printStackTrace();
562 582
			}
563 583
		}
564 584
		return result;
565 585
	}
566

  
586
	
567 587
	public static boolean stopEnginesManagers() {
568

  
588
		
569 589
		Log.finest("Stopping engines of the " + enginesManagers.keySet().size() + " engines managers...");
570

  
590
		
571 591
		if (enginesManagers == null) return true;
572 592
		if (enginesManagers.size() == 0) return true;
573

  
593
		
574 594
		boolean result = true;
575
		HashSet<EngineType> ets = new HashSet<EngineType>();
595
		HashSet<EngineType> ets = new HashSet<>();
576 596
		ets.addAll(enginesManagers.keySet());
577 597
		for (EngineType et : ets) {
578 598
			EnginesManager<?> enginesManager = enginesManagers.get(et);
......
580 600
			result = result && enginesManager.stopEngines();
581 601
			removeEngineManager(enginesManager); // remove the engine manager anyway
582 602
		}
583

  
603
		
584 604
		return true;
585 605
	}
586

  
587

  
588

  
606
	
607
	
608
	
589 609
	private static boolean startWorkspace(IProgressMonitor monitor) {
590

  
610
		
591 611
		String txmhomedir = getPreference(TBXPreferences.USER_TXM_HOME);
592 612
		if (txmhomedir == null || txmhomedir.length() == 0) {
593 613
			state = false;
594 614
			return false;
595 615
		}
596

  
616
		
597 617
		Version currentVersion = BundleUtils.getBundleVersion("org.txm.core");
598 618
		Log.fine(TXMCoreMessages.bind("Current toolbox version: {0}.", currentVersion));
599 619
		String installedVersionString = getPreference(TBXPreferences.VERSION);
......
603 623
		Version installedVersion = new Version(installedVersionString);
604 624
		Log.fine(TXMCoreMessages.bind("Installed toolbox version: {0}.", installedVersion));
605 625
		try {
606
			//System.out.println("Toolbox.startWorkspace(): workspace location = " + location);
607

  
626
			// System.out.println("Toolbox.startWorkspace(): workspace location = " + location);
627
			
608 628
			boolean doUpdateworkspace = currentVersion.compareTo(installedVersion) > 0;
609

  
629
			
610 630
			if (doUpdateworkspace) { // newer install
611 631
				Log.fine("Updating Toolbox workspace...");
612

  
632
				
613 633
				// create or update the workspace & create TXM default.xml workspace file
614
				Toolbox.workspace = createOrUpdate(new File(txmhomedir)); //$NON-NLS-1$
615

  
634
				Toolbox.workspace = createOrUpdate(new File(txmhomedir));
635
				
616 636
				// test
617 637
				if (Toolbox.workspace == null) {
618 638
					Log.severe("Error: workspace not updated (is null).");
619 639
					return false;
620 640
				}
621 641
				setPreference(TBXPreferences.VERSION, currentVersion.toString());
622
			} else { // already existing workspace
642
			}
643
			else { // already existing workspace
623 644
				workspace = Workspace.getInstance();
624 645
			}
625

  
626
			Log.fine(NLS.bind(TXMCoreMessages.loadingWorkspaceFromFileColonP0, txmhomedir)); 
646
			
647
			Log.fine(NLS.bind(TXMCoreMessages.loadingWorkspaceFromFileColonP0, txmhomedir));
627 648
			state = true;
628

  
629
			if (workspace == null) { //$NON-NLS-1$
630
				Log.severe(NLS.bind(TXMCoreMessages.errorLoadingWorkspaceFromFileColonP0, txmhomedir)); 
649
			
650
			if (workspace == null) {
651
				Log.severe(NLS.bind(TXMCoreMessages.errorLoadingWorkspaceFromFileColonP0, txmhomedir));
631 652
				state = false;
632
				//System.out.println(TXMCoreMessages.FAILED);
653
				// System.out.println(TXMCoreMessages.FAILED);
633 654
				return false;
634
			} else {
635
				//System.out.println(TXMCoreMessages.DONE);
655
			}
656
			else {
657
				// System.out.println(TXMCoreMessages.DONE);
636 658
				// updating extension files
637 659
				IConfigurationElement[] contributions = Platform.getExtensionRegistry().getConfigurationElementsFor(PostTXMHOMEInstallationStep.EXTENSION_ID);
638
				//System.out.println("contributions: "+Arrays.toString(contributions));
639
				Log.fine("Installing extensions ("+contributions.length+")");
660
				// System.out.println("contributions: "+Arrays.toString(contributions));
661
				Log.fine("Installing extensions (" + contributions.length + ")");
640 662
				for (int i = 0; i < contributions.length; i++) {
641 663
					try {
642 664
						Log.fine(TXMCoreMessages.bind("Installing extentions: {0}...", contributions[i].getName()));
643
						PostTXMHOMEInstallationStep extp = (PostTXMHOMEInstallationStep)contributions[i].createExecutableExtension("class"); //$NON-NLS-1$
644

  
665
						PostTXMHOMEInstallationStep extp = (PostTXMHOMEInstallationStep) contributions[i].createExecutableExtension("class"); //$NON-NLS-1$
666
						
645 667
						if (!extp.install(workspace)) {
646
							Log.severe("Fail to install "+extp.getName()+" files in "+workspace.getLocation());
668
							Log.severe("Fail to install " + extp.getName() + " files in " + workspace.getLocation());
647 669
						}
648
					} catch(CoreException e) {
670
					}
671
					catch (CoreException e) {
649 672
						e.printStackTrace();
650
					} 
673
					}
651 674
				}
652 675
			}
653
		} catch (Exception e) {
654
			Log.warning(NLS.bind(TXMCoreMessages.errorDuringWorkspaceInitializationColonP0, txmhomedir)); 
676
		}
677
		catch (Exception e) {
678
			Log.warning(NLS.bind(TXMCoreMessages.errorDuringWorkspaceInitializationColonP0, txmhomedir));
655 679
			Log.warning(NLS.bind(TXMCoreMessages.errorColonP0, Log.toString(e)));
656 680
			Log.printStackTrace(e);
657 681
			state = false;
658 682
		}
659 683
		return workspace != null;
660 684
	}
661

  
662
	/* (non-Javadoc)
685
	
686
	/*
687
	 * (non-Javadoc)
663 688
	 * @see java.lang.Object#finalize()
664 689
	 */
665 690
	@Override
666 691
	protected void finalize() throws Throwable {
667 692
		try {
668 693
			Toolbox.shutdown();
669
		} finally {
694
		}
695
		finally {
670 696
			super.finalize();
671 697
		}
672 698
	}
673

  
699
	
674 700
	/**
675 701
	 * Gets a Collator for the specified result.
676 702
	 * The collator is created from the parent of the result if exists and if its a TXMObject (from "lang" attribute) otherwise it is created from the default locale.
703
	 * 
677 704
	 * @param result
678
	 * @return 
705
	 * @return
679 706
	 */
680
	public static Collator getCollator(TXMResult result)	{
707
	public static Collator getCollator(TXMResult result) {
681 708
		Locale locale = Locale.getDefault();
682 709
		String lang = result.getStringParameterValue(TBXPreferences.LANG);
683 710
		if (lang != null) {
......
687 714
		collator.setStrength(Collator.TERTIARY);
688 715
		return collator;
689 716
	}
690

  
717
	
691 718
	public static String getMetadataEncoding() {
692 719
		return getPreference(TBXPreferences.METADATA_ENCODING);
693 720
	}
694
	public static String getMetadataColumnSeparator(){
721
	
722
	public static String getMetadataColumnSeparator() {
695 723
		return getPreference(TBXPreferences.METADATA_COLSEPARATOR);
696 724
	}
725
	
697 726
	public static String getMetadataTextSeparator() {
698 727
		return getPreference(TBXPreferences.METADATA_TXTSEPARATOR);
699 728
	}
700

  
729
	
701 730
	public static String getInstallDirectory() {
702 731
		return getPreference(TBXPreferences.INSTALL_DIR);
703 732
	}
704

  
733
	
705 734
	/**
706 735
	 * Creates&Update workspace directory.
707 736
	 * 
......
713 742
	public static Workspace createOrUpdate(File txmhomedir) {
714 743
		try {
715 744
			txmhomedir.mkdirs();
716

  
745
			
717 746
			if (!txmhomedir.exists()) {
718 747
				System.out.println(NLS.bind(TXMCoreMessages.couldNotCreateTXMHOMEDirectoryColonP0, txmhomedir));
719 748
				return null;
720 749
			}
721

  
750
			
722 751
			// create folders
723 752
			String createfolders[] = {
724 753
					"corpora", "clipboard", //$NON-NLS-1$ //$NON-NLS-2$
725
					"css", "xsl", "schema", "scripts"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
726
			String deletefolders[] = {"clipboard"}; //$NON-NLS-1$
727

  
754
					"css", "xsl", "schema", "scripts" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
755
			String deletefolders[] = { "clipboard" }; //$NON-NLS-1$
756
			
728 757
			for (String folder : deletefolders) {
729 758
				DeleteDir.deleteDirectory(new File(txmhomedir, folder));
730 759
			}
731

  
760
			
732 761
			for (String folder : createfolders) {
733 762
				new File(txmhomedir, folder).mkdir();
734 763
			}
735

  
736
			//			if (!xmlfile.exists()) {
737
			//				if (!writeEmptyWorkspaceFile(xmlfile)) {
738
			//					System.out.println("Error while creating workspace definition file: "+xmlfile);
739
			//				}
740
			//			}
741

  
764
			
765
			// if (!xmlfile.exists()) {
766
			// if (!writeEmptyWorkspaceFile(xmlfile)) {
767
			// System.out.println("Error while creating workspace definition file: "+xmlfile);
768
			// }
769
			// }
770
			
742 771
			String path = Toolbox.getPreference(TBXPreferences.INSTALL_DIR);
743 772
			File installDirectory = new File(path);
744 773
			if (!installDirectory.exists()) {
745
				Log.warning("Error: Workspace cannot found install directory: "+installDirectory.getAbsolutePath());
774
				Log.warning("Error: Workspace cannot found install directory: " + installDirectory.getAbsolutePath());
746 775
				return null;
747 776
			}
748

  
777
			
749 778
			File redistDirectory = new File(installDirectory, "redist");
750 779
			if (!redistDirectory.exists()) {
751
				Log.warning("Warning: Workspace cannot found redist directory: "+redistDirectory.getAbsolutePath());
752
			} else {
780
				Log.warning("Warning: Workspace cannot found redist directory: " + redistDirectory.getAbsolutePath());
781
			}
782
			else {
753 783
				FileCopy.copyFiles(redistDirectory, txmhomedir);
754 784
			}
755

  
756
			//			// the folders to copy from TXM install dir
757
			//			BundleUtils.copyFiles("org.txm.core", "res", "org/txm/xml", "xsl", txmhomedir);
758
			//			BundleUtils.copyFiles("org.txm.core", "res", "org/txm/xml", "schema", txmhomedir);
759
			//			BundleUtils.copyFiles("org.txm.core", "res", "org/txm", "css", txmhomedir);
760

  
785
			
786
			// // the folders to copy from TXM install dir
787
			// BundleUtils.copyFiles("org.txm.core", "res", "org/txm/xml", "xsl", txmhomedir);
788
			// BundleUtils.copyFiles("org.txm.core", "res", "org/txm/xml", "schema", txmhomedir);
789
			// BundleUtils.copyFiles("org.txm.core", "res", "org/txm", "css", txmhomedir);
790
			
761 791
			workspace = Workspace.getInstance();
762

  
792
			
763 793
			return workspace;
764
		} catch (Exception e) {
794
		}
795
		catch (Exception e) {
765 796
			Log.warning(NLS.bind(TXMCoreMessages.failedToCopyTXMFilesFromTXMINSTALLDIRToTXMHOMEColonP0, e.getLocalizedMessage()));
766 797
			e.printStackTrace();
767 798
			return null;
768 799
		}
769 800
	}
770

  
801
	
771 802
	public static ImportEngines getImportEngines() {
772 803
		return (ImportEngines) getEngineManager(EngineType.IMPORT);
773 804
	}
774

  
805
	
775 806
	public static LinkedHashMap<EngineType, EnginesManager<?>> getEngineManagers() {
776 807
		return enginesManagers;
777 808
	}
778

  
809
	
779 810
	/**
780 811
	 * Notify all engines about a result state
781 812
	 * 
......
783 814
	 * @param state
784 815
	 */
785 816
	public static void notifyEngines(TXMResult r, String state) {
786
		Log.fine("Toolbox.notifyEngines "+r+" -> "+state);
817
		Log.fine("Toolbox.notifyEngines " + r + " -> " + state);
787 818
		for (EnginesManager<?> em : enginesManagers.values()) {
788 819
			if (em == null) continue;
789 820
			for (Engine e : em.getEngines().values()) {
......
792 823
			}
793 824
		}
794 825
	}
795
}
826
}

Formats disponibles : Unified diff