Révision 2816

tmp/org.txm.rcp/src/main/java/org/txm/rcp/p2/plugins/TXMUpdateHandler.java (revision 2816)
9 9
import java.io.IOException;
10 10
import java.io.InputStream;
11 11
import java.io.InputStreamReader;
12
import java.io.OutputStream;
12 13
import java.io.OutputStreamWriter;
14
import java.io.PrintStream;
13 15
import java.net.MalformedURLException;
14 16
import java.net.URI;
15 17
import java.net.URL;
16 18
import java.util.Arrays;
17 19
import java.util.Iterator;
20
import java.util.prefs.Preferences;
18 21

  
19 22
import org.eclipse.core.commands.ExecutionEvent;
20 23
import org.eclipse.core.runtime.Assert;
......
51 54
import org.txm.utils.logger.Log;
52 55
import org.txm.utils.zip.GZip;
53 56

  
57
import static java.lang.System.setErr;
58
import static java.util.prefs.Preferences.systemRoot;
59

  
54 60
public class TXMUpdateHandler extends UpdateHandler {
55 61

  
56
	// public static final String UPDATESITE = "http://textometrie.ens-lyon.fr/dist"; //
62
	// public static final String UPDATESITE =
63
	// "http://textometrie.ens-lyon.fr/dist"; //
57 64
	// "file:"+System.getProperty("user.home")+"/TEMP/updates"; // LOCAL TEST ONLY
58 65
	public static final String ID = "org.txm.rcp.p2.plugins.TXMUpdateHandler";
59 66

  
......
75 82
					File installDirectory = new File(path);
76 83
					Log.fine("Testing install directory rights: " + installDirectory);
77 84
					if (!installDirectory.canWrite() || !installDirectory.canExecute()) {
78
						Log.warning(NLS.bind("Warning: you need administrator privileges to fully update TXM (installed in {0}). Some updates might not be fully installed.", installDirectory));
85
						Log.warning(NLS.bind(
86
								"Warning: you need administrator privileges to fully update TXM (installed in {0}). Some updates might not be fully installed.",
87
								installDirectory));
79 88
						return null;
80 89
					}
81
				}
82
				catch (Exception e) {
90
				} catch (Exception e) {
83 91
					// TODO Auto-generated catch block
84 92
					e.printStackTrace();
85 93
				}
86 94
			}
87 95
		}
88 96

  
89
		// Hacking p2 profile to be able to update installation directory even if -configuration is set
97
		// Hacking p2 profile to be able to update installation directory even if
98
		// -configuration is set
90 99
		try {
91 100
			ProvisioningUI pui = ProvisioningUI.getDefaultUI();
92 101

  
......
96 105
			if (agent != null) {
97 106
				IProfileRegistry profileRegistry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
98 107

  
99

  
100 108
				if (profileRegistry != null && profileRegistry instanceof SimpleProfileRegistry) {
101 109

  
102 110
					SimpleProfileRegistry spr = (SimpleProfileRegistry) profileRegistry;
......
133 141
			try {
134 142
				InputStream s = baseURL.openStream();
135 143
				s.close();
136
			}
137
			catch (Exception e) {
144
			} catch (Exception e) {
138 145
				Log.severe("Update site is not reachable: " + baseURL + ", aborting.");
139 146
				return false;
140 147
			}
......
150 157
			Log.info("Done.");
151 158

  
152 159
			return ret;
153
		}
154
		catch (Exception e) {
160
		} catch (Exception e) {
155 161
			Log.severe("Could not update TXM: " + e + ".");
156 162
			Log.printStackTrace(e);
157 163
		}
......
164 170
			return true; // TXM was not installed in program files no need to test admin user
165 171
		}
166 172

  
167
		return isAdminCommandTest();
173
		return isWindowsAdminCommandTest();
168 174
	}
169 175

  
170
	public static  boolean isAdminCommandTest() {
171
		StringBuilder outputbuilder = new StringBuilder();
172
		try {
173
			ProcessBuilder builder = new ProcessBuilder(
174
					"cmd.exe","/c" ,"net user");
175
			builder.redirectErrorStream(true);
176
			Process p = builder.start();
177
			BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
178
			String line;
179
			while (true) {
180
				line = r.readLine();
181
				if (line == null) { break; }
182
				outputbuilder.append(line);
183
			}
184
		} catch (IOException e) {
185
			e.printStackTrace();
186
			return false;
187
		}
188
		System.out.println(outputbuilder.toString());
189
		return outputbuilder.toString().contains("Administrator");
190
	}
176
	private static boolean isWindowsAdminCommandTest()
177
    {
178
        Preferences preferences = systemRoot();
191 179

  
180
        synchronized (System.err)
181
        {
182
            setErr(new PrintStream(new OutputStream() {
183
				@Override
184
				public void write(int b) throws IOException { }
185
			}));
186

  
187
            try
188
            {
189
                preferences.put("foo", "bar"); // SecurityException on Windows
190
                preferences.remove("foo");
191
                preferences.flush(); // BackingStoreException on Linux
192
                return true;
193
            } catch (Exception exception)
194
            {
195
                return false;
196
            } finally
197
            {
198
                setErr(System.err);
199
            }
200
        }
201
    }
202

  
192 203
	/**
193 204
	 * Return a shell appropriate for parenting dialogs of this handler.
194 205
	 * 
......
201 212
	}
202 213

  
203 214
	public static boolean patchGZProfile() {
204
		// TODO: is this still useful with TXM 0.7.7 -> yes&no : need to patch when --configuration is set, done by editing the Profile object directly
215
		// TODO: is this still useful with TXM 0.7.7 -> yes&no : need to patch when
216
		// --configuration is set, done by editing the Profile object directly
205 217
		String path = BundleUtils.getInstallDirectory();// System.getProperty("osgi.instance.area");
206 218
		URL location = null;
207 219
		try {
208 220
			location = new URL(path);
209
		}
210
		catch (MalformedURLException e) {
221
		} catch (MalformedURLException e) {
211 222
			Log.severe(NLS.bind(TXMUIMessages.switchLanguageColonMalformedUrlColonP0, location));
212 223
			return false;
213 224
		}
......
230 241
		if (gzFile == null) {
231 242
			Log.severe("No profile GZ file found");
232 243
			return false;
233
		}
234
		else {
244
		} else {
235 245
			try {
236 246
				// 2- extract profile from gz profile
237 247
				File profileXMLFile = GZip.uncompress(gzFile, profileDir);
......
255 265
				}
256 266
				Log.fine("Profile archive patched: " + gzFile);
257 267
				return true;
258
			}
259
			catch (IOException e) {
268
			} catch (IOException e) {
260 269
				Log.severe("Failed to fix profile file: " + e);
261 270
				Log.printStackTrace(e);
262 271
				return false;
......
274 283
			addURL(agent, repoUriDefault);
275 284
			// URI repoKepler = new URI("http://download.eclipse.org/releases/kepler");
276 285
			// addURL(agent, repoKepler);
277
		}
278
		catch (Exception e) {
286
		} catch (Exception e) {
279 287
			Log.severe("Could not add update default repository: " + uriDefault);
280 288
			Log.printStackTrace(e);
281 289
		}
......
286 294
		boolean devMode = false;
287 295
		if ("DEV".equals(updateLevel)) {//$NON-NLS-1$
288 296
			devMode = alphaMode = betaMode = true;
289
		}
290
		else if ("ALPHA".equals(updateLevel)) {//$NON-NLS-1$
297
		} else if ("ALPHA".equals(updateLevel)) {//$NON-NLS-1$
291 298
			alphaMode = betaMode = true;
292
		}
293
		else if ("BETA".equals(updateLevel)) {//$NON-NLS-1$
299
		} else if ("BETA".equals(updateLevel)) {//$NON-NLS-1$
294 300
			betaMode = true;
295 301
		}
296 302
		Log.fine("Update levels: dev=" + devMode + " alpha=" + alphaMode + " beta=" + betaMode);
......
300 306
			URI repoUriDev = new URI(uriDev);
301 307
			if (devMode) {
302 308
				addURL(agent, repoUriDev);
303
			}
304
			else {
309
			} else {
305 310
				removeURL(agent, repoUriDev);
306 311
			}
307
		}
308
		catch (Exception e) {
312
		} catch (Exception e) {
309 313
			Log.severe("Could not add update DEV repository: " + uriDev);
310 314
			e.printStackTrace();
311 315
		}
......
315 319
			URI repoUriAlpha = new URI(uriAlpha);
316 320
			if (alphaMode) {
317 321
				addURL(agent, repoUriAlpha);
318
			}
319
			else {
322
			} else {
320 323
				removeURL(agent, repoUriAlpha);
321 324
			}
322
		}
323
		catch (Exception e) {
325
		} catch (Exception e) {
324 326
			Log.severe("Could not add update ALPHA repository: " + uriAlpha);
325 327
			e.printStackTrace();
326 328
		}
......
330 332
			URI repoUriBeta = new URI(uriBeta);
331 333
			if (betaMode) {
332 334
				addURL(agent, repoUriBeta);
333
			}
334
			else {
335
			} else {
335 336
				removeURL(agent, repoUriBeta);
336 337
			}
337
		}
338
		catch (Exception e) {
338
		} catch (Exception e) {
339 339
			Log.severe("Can not add update BETA repository: " + uriBeta);
340 340
		}
341 341
	}
......
351 351
			addURL(agent, repoUriDefault);
352 352
			// URI repoKepler = new URI("http://download.eclipse.org/releases/kepler");
353 353
			// addURL(agent, repoKepler);
354
		}
355
		catch (Exception e) {
354
		} catch (Exception e) {
356 355
			Log.severe("Could not add update default repository: " + uriDefault);
357 356
			Log.printStackTrace(e);
358 357
		}
......
363 362
		boolean devMode = false;
364 363
		if ("DEV".equals(updateLevel)) {//$NON-NLS-1$
365 364
			devMode = alphaMode = betaMode = true;
366
		}
367
		else if ("ALPHA".equals(updateLevel)) {//$NON-NLS-1$
365
		} else if ("ALPHA".equals(updateLevel)) {//$NON-NLS-1$
368 366
			alphaMode = betaMode = true;
369
		}
370
		else if ("BETA".equals(updateLevel)) {//$NON-NLS-1$
367
		} else if ("BETA".equals(updateLevel)) {//$NON-NLS-1$
371 368
			betaMode = true;
372 369
		}
373 370
		Log.fine("Update levels: dev=" + devMode + " alpha=" + alphaMode + " beta=" + betaMode);
......
377 374
			URI repoUriDev = new URI(uriDev);
378 375
			if (devMode) {
379 376
				addURL(agent, repoUriDev);
380
			}
381
			else {
377
			} else {
382 378
				removeURL(agent, repoUriDev);
383 379
			}
384
		}
385
		catch (Exception e) {
380
		} catch (Exception e) {
386 381
			Log.severe("Could not add update DEV repository: " + uriDev);
387 382
			e.printStackTrace();
388 383
		}
......
392 387
			URI repoUriAlpha = new URI(uriAlpha);
393 388
			if (alphaMode) {
394 389
				addURL(agent, repoUriAlpha);
395
			}
396
			else {
390
			} else {
397 391
				removeURL(agent, repoUriAlpha);
398 392
			}
399
		}
400
		catch (Exception e) {
393
		} catch (Exception e) {
401 394
			Log.severe("Could not add update ALPHA repository: " + uriAlpha);
402 395
			e.printStackTrace();
403 396
		}
......
407 400
			URI repoUriBeta = new URI(uriBeta);
408 401
			if (betaMode) {
409 402
				addURL(agent, repoUriBeta);
410
			}
411
			else {
403
			} else {
412 404
				removeURL(agent, repoUriBeta);
413 405
			}
414
		}
415
		catch (Exception e) {
406
		} catch (Exception e) {
416 407
			Log.severe("Can not add update BETA repository: " + uriBeta);
417 408
		}
418 409

  
419 410
	}
420 411

  
421 412
	public static boolean addURL(IProvisioningAgent agent, URI location) {
422
		IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME);
423
		IArtifactRepositoryManager manager2 = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
413
		IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent
414
				.getService(IMetadataRepositoryManager.SERVICE_NAME);
415
		IArtifactRepositoryManager manager2 = (IArtifactRepositoryManager) agent
416
				.getService(IArtifactRepositoryManager.SERVICE_NAME);
424 417

  
425 418
		if (manager == null) {
426 419
			System.out.println("No metadata repository manager found");
......
436 429
		try {
437 430
			// manager.removeRepository(location)
438 431
			manager.loadRepository(location, null);
439
		}
440
		catch (Exception e) {
432
		} catch (Exception e) {
441 433
			Log.severe("No repo - create a newmetadata repo");
442 434
			// for convenience create and add a repository here
443 435
			String repositoryName = location + " - metadata";
444 436
			try {
445
				manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, null);
446
			}
447
			catch (ProvisionException e2) {
437
				manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY,
438
						null);
439
			} catch (ProvisionException e2) {
448 440
				Log.severe("Error while adding metadata repo: " + location);
449 441
				Log.printStackTrace(e);
450 442
				return false;
......
455 447
			// manager.removeRepository(location)
456 448
			manager2.loadRepository(location, null);
457 449
			return true;
458
		}
459
		catch (Exception e) {
450
		} catch (Exception e) {
460 451
			// could not load a repo at that location so create one as a convenience
461 452
			String repositoryName = location + " - artifacts";
462 453
			try {
463 454
				Log.severe("No repo - create a new artifact repo");
464
				manager.createRepository(location, repositoryName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, null);
455
				manager.createRepository(location, repositoryName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY,
456
						null);
465 457
				return true;
466
			}
467
			catch (Exception e2) {
458
			} catch (Exception e2) {
468 459
				Log.severe("Error while adding artifact repo: " + location);
469 460
				Log.printStackTrace(e);
470 461
				return false;
......
473 464
	}
474 465

  
475 466
	public static boolean removeURL(IProvisioningAgent agent, URI location) {
476
		IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME);
477
		IArtifactRepositoryManager manager2 = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
467
		IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent
468
				.getService(IMetadataRepositoryManager.SERVICE_NAME);
469
		IArtifactRepositoryManager manager2 = (IArtifactRepositoryManager) agent
470
				.getService(IArtifactRepositoryManager.SERVICE_NAME);
478 471

  
479 472
		if (manager == null) {
480 473
			Log.severe("No metadata repository manager found");
......
508 501
			String trimedLine = line.trim();
509 502
			if (trimedLine.startsWith("<property name='org.eclipse.equinox.p2.type.lock' value='")) {
510 503
				writer.write("<property name='org.eclipse.equinox.p2.type.lock' value='0'/>");
511
			}
512
			else {
504
			} else {
513 505
				writer.write(line);
514 506
			}
515 507
			firstLine = false;
......
532 524
			}
533 525
		});
534 526

  
535
		if (files == null || files.length == 0) return null;
527
		if (files == null || files.length == 0)
528
			return null;
536 529

  
537 530
		Arrays.sort(files);
538 531
		return files[files.length - 1];
......
559 552
	//// getProvisioningUI().openUpdateWizard(false, operation, job);
560 553
	//// } else {
561 554
	////
562
	//// final RemediationOperation remediationOperation = new RemediationOperation(getProvisioningUI().getSession(), operation.getProfileChangeRequest(),
555
	//// final RemediationOperation remediationOperation = new
556
	// RemediationOperation(getProvisioningUI().getSession(),
557
	// operation.getProfileChangeRequest(),
563 558
	// RemedyConfig.getCheckForUpdateRemedyConfigs());
564
	//// ProvisioningJob job2 = new ProvisioningJob(ProvSDKMessages.RemediationOperation_ResolveJobName, getProvisioningUI().getSession()) {
559
	//// ProvisioningJob job2 = new
560
	// ProvisioningJob(ProvSDKMessages.RemediationOperation_ResolveJobName,
561
	// getProvisioningUI().getSession()) {
565 562
	//// @Override
566 563
	//// public IStatus runModal(IProgressMonitor monitor) {
567
	//// monitor.beginTask(ProvSDKMessages.RemediationOperation_ResolveJobTask, RemedyConfig.getAllRemedyConfigs().length);
564
	//// monitor.beginTask(ProvSDKMessages.RemediationOperation_ResolveJobTask,
565
	// RemedyConfig.getAllRemedyConfigs().length);
568 566
	//// return remediationOperation.resolveModal(monitor);
569 567
	//// }
570 568
	//// };
......
573 571
	//// if (PlatformUI.isWorkbenchRunning()) {
574 572
	//// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
575 573
	//// public void run() {
576
	//// getProvisioningUI().openUpdateWizard(true, operation, remediationOperation, null);
574
	//// getProvisioningUI().openUpdateWizard(true, operation, remediationOperation,
575
	// null);
577 576
	//// }
578 577
	//// });
579 578
	//// }
......
586 585
	// }
587 586
	//
588 587
	// /**
589
	// * Answer a boolean indicating whether the caller should continue to work with the
590
	// * specified operation. This method is used when an operation has been resolved, but
588
	// * Answer a boolean indicating whether the caller should continue to work with
589
	// the
590
	// * specified operation. This method is used when an operation has been
591
	// resolved, but
591 592
	// * the UI may have further restrictions on continuing with it.
592 593
	// *
593 594
	// * @param operation the operation in question. It must already be resolved.
594 595
	// * @param shell the shell to use for any interaction with the user
595
	// * @return <code>true</code> if processing of the operation should continue, <code>false</code> if
596
	// * not. It is up to the implementor to report any errors to the user when answering <code>false</code>.
596
	// * @return <code>true</code> if processing of the operation should continue,
597
	// <code>false</code> if
598
	// * not. It is up to the implementor to report any errors to the user when
599
	// answering <code>false</code>.
597 600
	// */
598
	// public boolean continueWorkingWithOperation(ProfileChangeOperation operation, Shell shell) {
601
	// public boolean continueWorkingWithOperation(ProfileChangeOperation operation,
602
	// Shell shell) {
599 603
	// //System.out.println("Test if any update available");
600 604
	// Assert.isTrue(operation.getResolutionResult() != null);
601 605
	// IStatus status = operation.getResolutionResult();
......
612 616
	//
613 617
	// // there is no plan, so we can't continue. Report any reason found
614 618
	// if (operation.getProvisioningPlan() == null && !status.isOK()) {
615
	// StatusManager.getManager().handle(status, StatusManager.LOG | StatusManager.SHOW);
619
	// StatusManager.getManager().handle(status, StatusManager.LOG |
620
	// StatusManager.SHOW);
616 621
	//
617 622
	// return false;
618 623
	// }
......
621 626
	// return true;
622 627
	// }
623 628
	//
624
	// protected void doPostLoadBackgroundWork(IProgressMonitor monitor) throws OperationCanceledException {
629
	// protected void doPostLoadBackgroundWork(IProgressMonitor monitor) throws
630
	// OperationCanceledException {
625 631
	// operation = getProvisioningUI().getUpdateOperation(null, null);
626 632
	// // check for updates
627 633
	// IStatus resolveStatus = operation.resolveModal(monitor);
......
632 638
	// protected boolean preloadRepositories() {
633 639
	// hasNoRepos = false;
634 640
	// RepositoryTracker repoMan = getProvisioningUI().getRepositoryTracker();
635
	// if (repoMan.getKnownRepositories(getProvisioningUI().getSession()).length == 0) {
641
	// if (repoMan.getKnownRepositories(getProvisioningUI().getSession()).length ==
642
	// 0) {
636 643
	// hasNoRepos = true;
637 644
	// return false;
638 645
	// }
......
644 651
	// return ProvSDKMessages.UpdateHandler_ProgressTaskName;
645 652
	// }
646 653

  
647

  
648

  
649 654
}

Formats disponibles : Unified diff