Project

General

Profile

Download (28.6 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2007 EDIT
3
 * European Distributed Institute of Taxonomy
4
 * http://www.e-taxonomy.eu
5
 *
6
 * The contents of this file are subject to the Mozilla Public License Version 1.1
7
 * See LICENSE.TXT at the top of this package for the full license terms.
8
 */
9

    
10
package eu.etaxonomy.taxeditor.model;
11

    
12
import java.lang.reflect.InvocationTargetException;
13
import java.util.ArrayList;
14
import java.util.Collection;
15
import java.util.LinkedHashMap;
16
import java.util.List;
17
import java.util.TreeSet;
18
import java.util.UUID;
19

    
20
import org.apache.commons.lang.StringUtils;
21
import org.apache.log4j.Logger;
22
import org.eclipse.core.commands.ExecutionException;
23
import org.eclipse.core.commands.NotEnabledException;
24
import org.eclipse.core.commands.NotHandledException;
25
import org.eclipse.core.commands.common.NotDefinedException;
26
import org.eclipse.core.commands.operations.AbstractOperation;
27
import org.eclipse.core.commands.operations.IOperationHistory;
28
import org.eclipse.core.runtime.IAdaptable;
29
import org.eclipse.core.runtime.IProgressMonitor;
30
import org.eclipse.core.runtime.IStatus;
31
import org.eclipse.core.runtime.NullProgressMonitor;
32
import org.eclipse.core.runtime.OperationCanceledException;
33
import org.eclipse.core.runtime.Status;
34
import org.eclipse.core.runtime.SubProgressMonitor;
35
import org.eclipse.core.runtime.jobs.ISchedulingRule;
36
import org.eclipse.core.runtime.jobs.Job;
37
import org.eclipse.jface.action.IStatusLineManager;
38
import org.eclipse.jface.operation.IRunnableWithProgress;
39
import org.eclipse.jface.resource.ColorRegistry;
40
import org.eclipse.jface.resource.FontRegistry;
41
import org.eclipse.jface.viewers.IStructuredSelection;
42
import org.eclipse.jface.viewers.SelectionChangedEvent;
43
import org.eclipse.swt.graphics.Color;
44
import org.eclipse.swt.graphics.Font;
45
import org.eclipse.swt.widgets.Display;
46
import org.eclipse.swt.widgets.Shell;
47
import org.eclipse.ui.IEditorPart;
48
import org.eclipse.ui.IViewPart;
49
import org.eclipse.ui.IViewReference;
50
import org.eclipse.ui.IWorkbench;
51
import org.eclipse.ui.IWorkbenchPage;
52
import org.eclipse.ui.IWorkbenchPart;
53
import org.eclipse.ui.IWorkbenchWindow;
54
import org.eclipse.ui.PartInitException;
55
import org.eclipse.ui.PlatformUI;
56
import org.eclipse.ui.handlers.IHandlerService;
57
import org.eclipse.ui.ide.undo.WorkspaceUndoUtil;
58
import org.eclipse.ui.part.EditorPart;
59
import org.eclipse.ui.progress.IProgressConstants;
60
import org.eclipse.ui.progress.IProgressService;
61
import org.eclipse.ui.progress.IWorkbenchSiteProgressService;
62
import org.eclipse.ui.themes.ITheme;
63
import org.eclipse.ui.themes.IThemeManager;
64

    
65
import eu.etaxonomy.cdm.api.application.CdmApplicationState;
66
import eu.etaxonomy.cdm.api.service.IProgressMonitorService;
67
import eu.etaxonomy.cdm.common.monitor.IRemotingProgressMonitor;
68
import eu.etaxonomy.cdm.io.common.ExportResult;
69
import eu.etaxonomy.cdm.model.common.IEnumTerm;
70
import eu.etaxonomy.taxeditor.operation.AbstractPostOperation;
71
import eu.etaxonomy.taxeditor.operation.IFeedbackGenerator;
72
import eu.etaxonomy.taxeditor.operation.IPostMoniteredOperationEnabled;
73
import eu.etaxonomy.taxeditor.operation.IPostOperationEnabled;
74
import eu.etaxonomy.taxeditor.operation.RemotingCdmHandler;
75
import eu.etaxonomy.taxeditor.store.CdmStore;
76
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
77
import eu.etaxonomy.taxeditor.ui.dialog.ReportTextDialog;
78
import eu.etaxonomy.taxeditor.view.AbstractCdmDataViewer;
79
import eu.etaxonomy.taxeditor.view.detail.DetailsViewPart;
80
import eu.etaxonomy.taxeditor.view.supplementaldata.SupplementalDataViewPart;
81
import eu.etaxonomy.taxeditor.workbench.WorkbenchUtility;
82

    
83
/**
84
 *
85
 * @author n.hoffmann
86
 * @created 11.05.2009
87
 * @version 1.0
88
 */
89
public abstract class AbstractUtility {
90

    
91
    private static final Logger logger = Logger.getLogger(AbstractUtility.class);
92

    
93
    /** Constant <code>statusLineManager</code> */
94
    protected static IStatusLineManager statusLineManager;
95

    
96

    
97
    public static boolean closeAll() {
98
        if(getActivePage()!=null){
99
            return getActivePage().closeAllEditors(true);
100
        }
101
        return false;
102
    }
103

    
104
    /**
105
     * Close the given editor.
106
     *
107
     * @param editor
108
     *            The <tt>MultipageTaxonEditor</tt> to close.
109
     * @return <tt>true</tt> on success
110
     */
111
    public static boolean close(EditorPart editor) {
112
        return getActivePage() != null ? getActivePage().closeEditor(editor, true):false;
113
    }
114

    
115
    public static Shell getShell() {
116

    
117
        return TaxeditorStorePlugin.getDefault().getWorkbench()
118
                .getActiveWorkbenchWindow().getShell();
119
    }
120

    
121
    public static IWorkbenchPage getActivePage() {
122
        try{
123
            return TaxeditorStorePlugin.getDefault().getWorkbench()
124
                    .getActiveWorkbenchWindow().getActivePage();
125
        } catch(NullPointerException npe){
126
            return null;
127
        }
128
    }
129

    
130
    public static IWorkbenchPart getActiveWorkbenchPart() {
131
        IWorkbenchPage activePage = getActivePage();
132
        if(activePage!=null){
133
            IWorkbenchPart activePart = activePage.getActivePart();
134
            if(activePart!=null){
135
                return activePart;
136
            }
137
        }
138
        return null;
139
    }
140

    
141
    public static Object getActiveE4Part() {
142
        IWorkbenchPage activePage = getActivePage();
143
        if(activePage!=null){
144
            IWorkbenchPart activePart = activePage.getActivePart();
145
            Object e4WrappedPart = WorkbenchUtility.getE4WrappedPart(activePart);
146
            return e4WrappedPart!=null?e4WrappedPart:activePart;
147
        }
148
        return null;
149
    }
150

    
151
    public static IWorkbench getWorkbench() {
152
        return TaxeditorStorePlugin.getDefault().getWorkbench();
153
    }
154

    
155
    public static IWorkbenchWindow getWorkbenchWindow() {
156
        if (getWorkbench().getWorkbenchWindowCount() > 1) {
157
            throw new IllegalStateException("More than one workbench window");
158
        }
159
        return getWorkbench().getWorkbenchWindows()[0];
160
    }
161

    
162
    public static IViewPart showView(String id) {
163
        try {
164
            return PlatformUI.getWorkbench().getActiveWorkbenchWindow()
165
                    .getActivePage()
166
                    .showView(id, null, IWorkbenchPage.VIEW_VISIBLE);
167
        } catch (PartInitException e) {
168
            MessagingUtils.messageDialog("Error opening view", AbstractUtility.class, "Could not open view: " + id, e);
169
            return null;
170
        }
171
    }
172

    
173
    public static void hideView(IViewPart view) {
174
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
175
        .hideView(view);
176
    }
177

    
178
    public static IViewPart getView(String id, boolean restore) {
179
    	IWorkbench workbench = PlatformUI.getWorkbench();
180
        IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
181
    	IViewReference[] references = null;
182
    	if(activeWorkbenchWindow!=null && activeWorkbenchWindow.getActivePage()!=null){
183
    	    references = activeWorkbenchWindow.getActivePage().getViewReferences();
184
    	}
185
    	else if(workbench.getWorkbenchWindows().length>0 && workbench.getWorkbenchWindows()[0].getActivePage()!=null){
186
    		references = workbench.getWorkbenchWindows()[0].getActivePage().getViewReferences();
187
    	}
188
    	if(references!=null){
189
    		for (IViewReference reference : references) {
190
    			if (reference.getId().equals(id)) {
191
    				return reference.getView(restore);
192
    			}
193
    		}
194
    	}
195
        return null;
196
    }
197

    
198
    public static Object getService(Class api) {
199
        return TaxeditorStorePlugin.getDefault().getWorkbench().getService(api);
200
    }
201

    
202
    public static ITheme getCurrentTheme() {
203
        IThemeManager themeManager = TaxeditorStorePlugin.getDefault()
204
                .getWorkbench().getThemeManager();
205
        return themeManager.getCurrentTheme();
206
    }
207

    
208
    /**
209
     * Fonts registered to the plugin may be obtained with the Eclipse themeing
210
     * functionality. Thus fonts are chooseable by the user via
211
     * Preferences->General->Appearance->Colors and Fonts
212
     *
213
     * @return the FontRegistry for the current theme
214
     */
215
    public static FontRegistry getFontRegistry() {
216
        return getCurrentTheme().getFontRegistry();
217
    }
218

    
219
    public static Font getFont(String symbolicName) {
220
        return getFontRegistry().get(symbolicName);
221
    }
222

    
223
    /**
224
     * Color registered to the plugin may be obtained with the Eclipse themeing
225
     * functionality. Thus colors are editable by the user via
226
     * Preferences->General->Appearance->Colors and Fonts
227
     *
228
     * @return the ColorRegistry for the current theme
229
     */
230
    public static ColorRegistry getColorRegistry() {
231
        return getCurrentTheme().getColorRegistry();
232
    }
233

    
234
    public static Color getColor(String symbolicName) {
235
        return getColorRegistry().get(symbolicName);
236
    }
237

    
238
    public static IStatus executeOperation(final AbstractPostOperation operation) {
239
        if (getOperationHistory() == null) {
240
            throw new IllegalArgumentException(
241
                    "There is no operation history for this context");
242
        }
243

    
244
        final IAdaptable uiInfoAdapter = WorkspaceUndoUtil
245
                .getUIInfoAdapter(getShell());
246

    
247
        IRunnableWithProgress runnable = new IRunnableWithProgress() {
248

    
249
            @Override
250
            public void run(IProgressMonitor monitor)
251
                    throws InvocationTargetException, InterruptedException {
252
                String operationlabel = operation.getLabel();
253
                monitor.beginTask(operationlabel, 100);
254
                IStatus status = Status.CANCEL_STATUS;
255
                try {
256
                    operation.addContext(IOperationHistory.GLOBAL_UNDO_CONTEXT);
257
                    status = getOperationHistory().execute(operation, monitor,
258
                            uiInfoAdapter);
259
                } catch (ExecutionException e) {
260

    
261
                    MessagingUtils.operationDialog(this, e, TaxeditorStorePlugin.PLUGIN_ID, operationlabel, null);
262

    
263
                } finally {
264
                    monitor.done();
265
                }
266

    
267
                String statusString = status.equals(Status.OK_STATUS) ? "completed"
268
                        : "cancelled";
269
                setStatusLine(operationlabel + " " + statusString + ".");
270

    
271
            }
272
        };
273

    
274
        try {
275
            runInUI(runnable, null);
276
        } catch (Exception e) {
277
            MessagingUtils.messageDialog("Error executing operation", AbstractUtility.class, "An error occured while executing " + operation.getLabel(), e);
278
        }
279

    
280
        IPostOperationEnabled postOperationEnabled = operation
281
                .getPostOperationEnabled();
282
        if (postOperationEnabled != null) {
283
            postOperationEnabled.onComplete();
284
        }
285
        return Status.OK_STATUS;
286
    }
287

    
288
    public static IStatus executeOperation(final AbstractOperation operation, final RemotingCdmHandler handler) {
289
        if (getOperationHistory() == null) {
290
            throw new IllegalArgumentException(
291
                    "There is no operation history for this context");
292
        }
293

    
294
        final IAdaptable uiInfoAdapter = WorkspaceUndoUtil
295
                .getUIInfoAdapter(getShell());
296

    
297
        IRunnableWithProgress runnable = new IRunnableWithProgress() {
298

    
299
            @Override
300
            public void run(IProgressMonitor monitor)
301
                    throws InvocationTargetException, InterruptedException {
302
                String operationlabel = operation.getLabel();
303
                monitor.beginTask(operationlabel, 100);
304
                IStatus status = Status.CANCEL_STATUS;
305
                try {
306
                    operation.addContext(IOperationHistory.GLOBAL_UNDO_CONTEXT);
307
                    status = getOperationHistory().execute(operation, monitor,
308
                            uiInfoAdapter);
309
                    if(handler != null) {
310
                        handler.postOperation(status);
311
                    }
312
                } catch (ExecutionException e) {
313
                    MessagingUtils.operationDialog(this, e, TaxeditorStorePlugin.PLUGIN_ID, operationlabel, null);
314
                } finally {
315
                    monitor.done();
316
                }
317

    
318
                String statusString = status.equals(Status.OK_STATUS) ? "completed"
319
                        : "cancelled";
320
                setStatusLine(operationlabel + " " + statusString + ".");
321

    
322
            }
323
        };
324

    
325
        try {
326
            runInUI(runnable, null);
327
        } catch (Exception e) {
328
            MessagingUtils.messageDialog("Error executing operation", AbstractUtility.class, "An error occured while executing " + operation.getLabel(), e);
329
        }
330

    
331
        return Status.OK_STATUS;
332
    }
333

    
334
    /**
335
     * Executes a remoting monitored operation
336
     *
337
     * @param label for the operation
338
     * @param uuid of the remoting monitor already started on the server
339
     * @param pollInterval in milliseconds
340
     * @param cancelable flag which determines whether the operation can be cancelled
341
     * @param postOp callback for running post operation logic
342
     * @return
343
     */
344
    public static IStatus executeMoniteredOperation(final String label,
345
            final UUID uuid,
346
            final int pollInterval,
347
            final boolean cancelable,
348
            final IPostMoniteredOperationEnabled postOp,
349
            final IFeedbackGenerator feedbackGenerator) {
350

    
351
        try {
352
            // get the remoting monitor the first time to make sure that the
353
            // operation is valid
354
            final IProgressMonitorService progressMonitorService = CdmApplicationState.getCurrentAppConfig().getProgressMonitorService();
355
            final IRemotingProgressMonitor firstRemotingMonitor = progressMonitorService.getRemotingMonitor(uuid);
356
            if(firstRemotingMonitor == null) {
357
                throw new IllegalStateException("Remoting progress monitor is null");
358
            }
359

    
360
            Job job = new Job(label) {
361

    
362

    
363
                @Override
364
                public IStatus run(IProgressMonitor monitor) {
365
                    // run the monitor until the operation is finished
366
                	monitor.beginTask("Start", 100);
367
                    IRemotingProgressMonitor remotingMonitor;
368
                    try {
369
                        remotingMonitor = CdmStore.getProgressMonitorClientManager().pollMonitor(label,
370
                                uuid,
371
                                pollInterval,
372
                                postOp,
373
                                feedbackGenerator,
374
                                monitor);
375
                    } catch (Exception ex) {
376
                        return new Status(Status.ERROR, TaxeditorStorePlugin.PLUGIN_ID, "Operation Interrupted", ex);
377
                    }
378
                    final StringBuilder reportSb = new StringBuilder();
379
                    // collect reports
380
//                    for(String report : remotingMonitor.getResult()) {
381
                        reportSb.append(((ExportResult)remotingMonitor.getResult()).createReport());
382
//                    }
383
                    if(!StringUtils.isBlank(reportSb.toString())) {
384
                        Display.getDefault().asyncExec(new Runnable() {
385
                            @Override
386
                            public void run() {
387
                                // display reports with possibility to save
388
                                ReportTextDialog dialog = new ReportTextDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
389
                                dialog.setTitle(label + " Report");
390
                                dialog.setReportText(reportSb.toString());
391
                                dialog.open();
392
                            }
393
                        });
394
                    }
395
                    return Status.OK_STATUS;
396
                }
397

    
398
                @Override
399
                protected void canceling() {
400
                    CdmStore.getCurrentApplicationConfiguration().getProgressMonitorService().cancel(uuid);
401
                }
402
            };
403

    
404
            // configure the job
405
            job.setProperty(IProgressConstants.KEEP_PROPERTY, true);
406
            job.setUser(true);
407
            // schedule job
408
            job.schedule();
409

    
410
        } catch (Exception e) {
411
            MessagingUtils.errorDialog("Error executing operation",
412
                    AbstractUtility.class,
413
                    "An error occured while executing " + label,
414
                    TaxeditorStorePlugin.PLUGIN_ID,
415
                    e,
416
                    true);
417
        }
418

    
419
        return Status.OK_STATUS;
420
    }
421

    
422
    public static IOperationHistory getOperationHistory() {
423
        return getWorkbench().getOperationSupport().getOperationHistory();
424
    }
425

    
426
    public static void setStatusLine(final String message) {
427
        Display.getDefault().asyncExec(new Runnable() {
428

    
429
            @Override
430
            public void run() {
431
                statusLineManager.setMessage(message);
432
            }
433

    
434
        });
435

    
436
    }
437

    
438
    public static IProgressMonitor getMonitor() {
439
        statusLineManager.setCancelEnabled(false);
440
        return statusLineManager.getProgressMonitor();
441
    }
442

    
443
    /**
444
     * Starts either the given {@link IProgressMonitor} if it's not
445
     * <code>null</code> or a new {@link NullProgressMonitor}.
446
     *
447
     * @param progressMonitor
448
     *            The {@link IProgressMonitor} or <code>null</code> if no
449
     *            progress should be reported.
450
     * @param taskName
451
     *            The name of the main task.
452
     * @param steps
453
     *            The number of steps this task is subdivided into.
454
     * @return The {@link IProgressMonitor}.
455
     */
456
    public static IProgressMonitor startMainMonitor(
457
            IProgressMonitor progressMonitor, String taskName, int steps) {
458
        IProgressMonitor newMonitor = progressMonitor;
459
        if (newMonitor == null) {
460
            newMonitor = new NullProgressMonitor();
461
        }
462
        newMonitor.beginTask(taskName == null ? "" : taskName, steps);
463
        newMonitor.subTask(" ");
464
        return newMonitor;
465
    }
466

    
467
    /**
468
     * Creates a {@link SubProgressMonitor} if the given
469
     * {@link IProgressMonitor} is not <code>null</code> and not a
470
     * {@link NullProgressMonitor}.
471
     *
472
     * @param progressMonitor
473
     *            The parent {@link IProgressMonitor} of the
474
     *            {@link SubProgressMonitor} to be created.
475
     * @param ticks
476
     *            The number of steps this subtask is subdivided into. Must be a
477
     *            positive number and must not be
478
     *            {@link IProgressMonitor#UNKNOWN}.
479
     * @return The {@link IProgressMonitor}.
480
     */
481
    public static IProgressMonitor getSubProgressMonitor(
482
            IProgressMonitor progressMonitor, int ticks) {
483
        if (progressMonitor == null) {
484
            return new NullProgressMonitor();
485
        }
486
        if (progressMonitor instanceof NullProgressMonitor) {
487
            return progressMonitor;
488
        }
489

    
490
        return new SubProgressMonitor(progressMonitor, ticks);
491
    }
492

    
493
    /**
494
     * Checks whether the user canceled this operation. If not canceled, the
495
     * given number of steps are declared as done.
496
     *
497
     * @param newMonitor
498
     *            a {@link org.eclipse.core.runtime.IProgressMonitor} object.
499
     * @param steps
500
     *            a int.
501
     */
502
    public static void workedChecked(IProgressMonitor newMonitor, int steps) {
503
        // In case the progress monitor was canceled throw an exception.
504
        if (newMonitor.isCanceled()) {
505
            throw new OperationCanceledException();
506
        }
507
        // Otherwise declare this step as done.
508
        newMonitor.worked(steps);
509
    }
510

    
511
    /**
512
     * Present a progress dialog to the user. This dialog will block the UI
513
     *
514
     * @param runnable
515
     *            an implementation of {@link IRunnableWithProgress}
516
     * @throws java.lang.InterruptedException
517
     *             if any.
518
     * @throws java.lang.reflect.InvocationTargetException
519
     *             if any.
520
     */
521
    public static void busyCursorWhile(IRunnableWithProgress runnable)
522
            throws InvocationTargetException, InterruptedException {
523
        getProgressService().busyCursorWhile(runnable);
524
    }
525

    
526
    public static void runInUI(IRunnableWithProgress runnable,
527
            ISchedulingRule rule) throws InvocationTargetException,
528
            InterruptedException {
529
        getProgressService().runInUI(getWorkbenchWindow(), runnable, rule);
530
    }
531

    
532
    public static void run(boolean fork, boolean cancelable,
533
            IRunnableWithProgress runnable) throws InvocationTargetException,
534
            InterruptedException {
535
        getProgressService().run(fork, cancelable, runnable);
536
    }
537

    
538
    public static IProgressService getProgressService() {
539
        IWorkbench workbench = PlatformUI.getWorkbench();
540
        return workbench.getProgressService();
541
    }
542

    
543
    public static IWorkbenchSiteProgressService getProgressService2() {
544
        return (IWorkbenchSiteProgressService) getService(IWorkbenchSiteProgressService.class);
545
    }
546

    
547
    public static String getPluginId() {
548
        return "eu.taxeditor";
549
    }
550

    
551
    public static IEditorPart getActiveEditor() {
552
        return getActivePage() != null ? getActivePage().getActiveEditor()
553
                : null;
554
    }
555

    
556
    public static Object getActiveE4Editor() {
557
        if(getActivePage()!=null){
558
            IEditorPart activeEditor = getActivePage().getActiveEditor();
559
            Object wrappedPart = WorkbenchUtility.getE4WrappedPart(getActivePage().getActivePart());
560
            return wrappedPart!=null?wrappedPart:activeEditor;
561
        }
562
        return null;
563
    }
564

    
565
    public static DetailsViewPart getDetailsView() {
566
        return (DetailsViewPart) getView(DetailsViewPart.ID, false);
567
    }
568

    
569
    public static void refreshDetailsViewer() {
570
        if (getDetailsView() != null) {
571
            ((AbstractCdmDataViewer) getDetailsView().getViewer()).refresh();
572
        }
573
    }
574

    
575
    public static void reflowDetailsViewer() {
576
        if (getDetailsView() != null) {
577
            ((AbstractCdmDataViewer) getDetailsView().getViewer()).reflow();
578
        }
579
    }
580

    
581
    public static SupplementalDataViewPart getSupplementalDataView() {
582
        return (SupplementalDataViewPart) getView(SupplementalDataViewPart.ID,
583
                false);
584
    }
585

    
586
    public static void reflowSupplementalViewer() {
587
        if (getSupplementalDataView() != null) {
588
            ((AbstractCdmDataViewer) getSupplementalDataView().getViewer())
589
            .reflow();
590
        }
591
    }
592

    
593

    
594
    /**
595
     * Orders a Collection of {@link IEnumTerm}s according to the term
596
     * hierarchy. <br>
597
     * <br>
598
     * The returned map will be be ordered primarily by root elements,
599
     * secondarily by the child elements and their children resp., both ascending alphabetically. <br>
600
     * @param terms
601
     *            A {@link Collection} of {@link IEnumTerm}s for which the term
602
     *            hierarchy should be created
603
     * @return a map which holds the terms as keys and their string
604
     *         representation via {@link IEnumTerm#getMessage()} as values
605
     */
606
    public static <T extends IEnumTerm<T>> LinkedHashMap<T, String> orderTerms(Collection<T> terms) {
607
        TreeSet<TermNode<T>> parentElements = new TreeSet<TermNode<T>>();
608
        parentElements.addAll(getTermHierarchy(terms));
609

    
610
        // create list according to the type hierarchy (root elements alphabetically with recursive children also alphabetically)
611
        LinkedHashMap<T, String> result = new LinkedHashMap<T, String>();
612
        parseTermTree(parentElements, result, -1);
613
        return result;
614
    }
615

    
616
    private static<T extends IEnumTerm<T>> void parseTermTree(Collection<TermNode<T>> children, LinkedHashMap<T, String> result, int depth){
617
        depth++;
618
        for(TermNode<T> node:children){
619
            String indentString = "";
620
            for(int i=0;i<depth;i++){
621
                indentString += "  ";
622
            }
623
            if(depth>0){
624
                indentString += "- ";
625
            }
626
            result.put(node.term, indentString + node.term.getMessage());
627
            parseTermTree(node.children, result, depth);
628
        }
629
    }
630

    
631
    private static<T extends IEnumTerm<T>> void addToParents(List<TermNode<T>> parents, Collection<T> terms){
632
        List<TermNode<T>> hasChildrenList = new ArrayList<TermNode<T>>();
633
        for(T term:terms){
634
            // only terms with parents
635
            if(term.getKindOf()!=null){
636
                TermNode<T> parentNode = new TermNode<T>(term.getKindOf());
637
                TermNode<T> childNode = new TermNode<T>(term);
638
                if(parents.contains(parentNode)){
639
                    // parent found in parent list -> add this term to parent's child list
640
                    parents.get(parents.indexOf(parentNode)).addChild(childNode);
641
                    if(!term.getGeneralizationOf().isEmpty()){
642
                        // has more children -> add to list which will be the parent for the next recursion
643
                        hasChildrenList.add(childNode);
644
                    }
645
                }
646
            }
647
        }
648
        if(!hasChildrenList.isEmpty()){
649
            addToParents(hasChildrenList, terms);
650
        }
651
    }
652

    
653
    private static<T extends IEnumTerm<T>> List<TermNode<T>> getTermHierarchy(Collection<T> terms){
654
        List<TermNode<T>> parents = new ArrayList<TermNode<T>>();
655
        // get root elements
656
        for(T term:terms){
657
            T parentTerm = term.getKindOf();
658
            if(parentTerm==null){
659
                // root element
660
                parents.add(new TermNode<T>(term));
661
            }
662
        }
663
        addToParents(parents, terms);
664
        return parents;
665
    }
666

    
667
    @SuppressWarnings("unchecked")
668
    /**
669
     * Recursively iterates over all term parents until no more parent is found i.e. the root node
670
     * @param term The term for which the parent should be found
671
     * @return the root terms of the term hierarchy
672
     */
673
    private static<T extends IEnumTerm<T>> T getParentFor(T term){
674
        // PP: cast should be safe. Why is Eclipse complaining??
675
        T parent = term.getKindOf();
676
        if(parent==null){
677
            return term;
678
        }
679
        else{
680
            return getParentFor(term.getKindOf());
681
        }
682
    }
683

    
684
    private static class TermNode<T extends IEnumTerm<T>> implements Comparable<TermNode<T>>{
685
        private final T term;
686
        private final TreeSet<TermNode<T>> children;
687

    
688
        public TermNode(T term) {
689
            super();
690
            this.term = term;
691
            this.children = new TreeSet<TermNode<T>>();
692
        }
693

    
694
        public void addChild(TermNode<T> child){
695
            this.children.add(child);
696
        }
697

    
698
        public TreeSet<TermNode<T>> getChildren() {
699
            return children;
700
        }
701

    
702
        public T getTerm() {
703
            return term;
704
        }
705

    
706
        @Override
707
        public int hashCode() {
708
            final int prime = 31;
709
            int result = 1;
710
            result = prime * result + ((term == null) ? 0 : term.hashCode());
711
            return result;
712
        }
713

    
714
        @Override
715
        public boolean equals(Object obj) {
716
            if (this == obj) {
717
                return true;
718
            }
719
            if (obj == null) {
720
                return false;
721
            }
722
            if (getClass() != obj.getClass()) {
723
                return false;
724
            }
725
            TermNode other = (TermNode) obj;
726
            if (term == null) {
727
                if (other.term != null) {
728
                    return false;
729
                }
730
            } else if (!term.equals(other.term)) {
731
                return false;
732
            }
733
            return true;
734
        }
735

    
736
        @Override
737
        public int compareTo(TermNode<T> that) {
738
            return this.term.getMessage().compareTo(that.term.getMessage());
739
        }
740
    }
741

    
742

    
743
    public static void executeCommand(String commandId, Object source, String pluginId) {
744
        IHandlerService handlerService = (IHandlerService) AbstractUtility.getService(IHandlerService.class);
745
        Exception exception = null;
746
        try {
747
            handlerService.executeCommand(commandId, null);
748
        } catch (ExecutionException e) {
749
            exception = e;
750
        } catch (NotDefinedException e) {
751
            exception = e;
752
        } catch (NotEnabledException e) {
753
            exception = e;
754
        } catch (NotHandledException e) {
755
            exception = e;
756
        } finally {
757
            if(exception != null) {
758
                MessagingUtils.errorDialog("Error executing command",
759
                        source,
760
                        "Could not execute command with id " + commandId ,
761
                        pluginId,
762
                        exception,
763
                        true);
764
            }
765
        }
766
    }
767

    
768
    public static Object getElementsFromSelectionChangedEvent(SelectionChangedEvent event) {
769
        IStructuredSelection selection = (IStructuredSelection) event.getSelection();
770
        Object selectionToSet = selection;
771
        if(selection.size() == 1){
772
            selectionToSet = selection.getFirstElement();
773
        }
774
        else if(!selection.isEmpty()){
775
            selectionToSet = selection.toArray();
776
        }
777
        return selectionToSet;
778
    }
779
}
(2-2/39)