Project

General

Profile

Download (22.7 KB) Statistics
| Branch: | Tag: | Revision:
1
package eu.etaxonomy.taxeditor.model;
2

    
3
import java.io.PrintWriter;
4
import java.io.StringWriter;
5
import java.time.LocalDateTime;
6
import java.time.format.DateTimeFormatter;
7
import java.util.ArrayList;
8
import java.util.List;
9

    
10
import org.apache.commons.lang3.exception.ExceptionUtils;
11
import org.apache.logging.log4j.LogManager;
12
import org.apache.logging.log4j.Logger;
13
import org.eclipse.core.runtime.IStatus;
14
import org.eclipse.core.runtime.MultiStatus;
15
import org.eclipse.core.runtime.Platform;
16
import org.eclipse.core.runtime.Status;
17
import org.eclipse.jface.dialogs.MessageDialog;
18
import org.eclipse.swt.widgets.Display;
19

    
20
import eu.etaxonomy.cdm.common.CdmUtils;
21
import eu.etaxonomy.cdm.config.ICdmSource;
22
import eu.etaxonomy.cdm.persistence.permission.SecurityExceptionUtils;
23
import eu.etaxonomy.taxeditor.remoting.RemoteExecutionTimestampsUtil;
24
import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
25
import eu.etaxonomy.taxeditor.store.CdmStore;
26
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
27

    
28
/**
29
 * Utility class which handles all the messaging information generated by the
30
 * Editor.
31
 *
32
 * This includes logging as well as dialogs.
33
 *
34
 * @author cmathew
35
 */
36
public class MessagingUtils {
37

    
38
    public final static String UNEXPECTED_ERROR_MESSAGE = "An error occurred.";
39
    public final static String CONTACT_MESSAGE = System.getProperty("line.separator") +  "Please contact EDIT Support (EditSupport@bgbm.org) with the error trace below (click on the 'Details' button).";
40
    public final static String DEFAULT_MESSAGE = "Error thrown but no associated message";
41
    public final static String CONNECTION_FAILURE_MESSAGE = "The connection to the remote server has been broken";
42
    public final static String REMOTE_ACCESS_FAILURE_MESSAGE = "Maybe the server is currently not available. If the problem persists please contact the server admin with the error trace below.";
43
    public static final String WIDGET_IS_DISPOSED_MESSAGE = "A widget was called, which was already disposed";
44
    public static final String ACCESS_DENIED = "The connection to the server could not be established because the access was denied.";
45
    public static final String PERMISSION_DENIED = "You do not have the permission to ";
46
    public static final String RESTART_EDITOR_MESSAGE = "An error occured that may require restarting the editor.";
47
    /**
48
     * Gets the Log4J logger for a given class
49
     *
50
     * @param clazz
51
     *            a {@link java.lang.Class} object.
52
     * @return a {@link org.apache.logging.log4j.Logger} object.
53
     */
54
    public static Logger getLog4JLogger(Class<?> clazz) {
55
        return LogManager.getLogger(clazz);
56
    }
57

    
58
    /**
59
     * Logs details from a given Status object
60
     *
61
     * @param status
62
     * 				a {@link org.eclipse.core.runtime.IStatus} object.
63
     */
64
    private static void log(IStatus status) {
65
        TaxeditorStorePlugin.getDefault().getLog().log(status);
66
    }
67

    
68
    /**
69
     * Logs a status object as information.
70
     *
71
     * @param status
72
     *            a {@link org.eclipse.core.runtime.IStatus} object.
73
     */
74
    public static void info(IStatus status) {
75
        log(status);
76
    }
77

    
78
    /**
79
     * Logs a string as information.
80
     *
81
     * @param message
82
     *            a {@link java.lang.String} object.
83
     */
84
    public static void info(String message) {
85
        IStatus status = new Status(IStatus.INFO, AbstractUtility.getPluginId(), message);
86
        info(status);
87
    }
88

    
89
    /**
90
     * Logs an exception from a given source as a warning.
91
     */
92
    public static void warn(Class<?> source, Throwable t) {
93
        IStatus status = new Status(IStatus.WARNING, AbstractUtility.getPluginId(), t.getMessage(), t);
94
        MessagingUtils.getLog4JLogger(source).warn(t);
95
        log(status);
96
    }
97

    
98
    /**
99
     * Logs a status object from a given source as a warning.
100
     */
101
    public static void warn(Class<?> source, IStatus status) {
102
        MessagingUtils.getLog4JLogger(source).warn(status.getMessage(), status.getException());
103
        log(status);
104
    }
105

    
106
    /**
107
     * Logs a string from a given source as a warning.
108
     *
109
     *
110
     * @param source
111
     *            a {@link java.lang.Class} object.
112
     * @param message
113
     *            a {@link java.lang.String} object.
114
     */
115
    public static void warn(Class<?> source, String message) {
116
        IStatus status = new Status(IStatus.WARNING, AbstractUtility.getPluginId(), message);
117
        MessagingUtils.getLog4JLogger(source).warn(message);
118
        log(status);
119
    }
120

    
121
    /**
122
     * Logs a status object from a given source as an error.
123
     *
124
     *
125
     * @param source
126
     *            a {@link java.lang.Class} object.
127
     * @param status
128
     *            a {@link org.eclipse.core.runtime.IStatus} object.
129
     */
130
    public static void error(Class<?> source, IStatus status) {
131
        getLog4JLogger(source)
132
        .error(status.getMessage(), status.getException());
133
        log(status);
134
    }
135

    
136
    /**
137
     * Logs a string and exception from a given source as an error.
138
     *
139
     *
140
     * @param source
141
     *            a {@link java.lang.Class} object.
142
     * @param message
143
     *            a {@link java.lang.String} object.
144
     * @param t
145
     *            a {@link java.lang.Throwable} object.
146
     */
147
    public static void error(Class<?> source, String message, Throwable t) {
148
        IStatus status = new Status(IStatus.ERROR, AbstractUtility.getPluginId(), message, t);
149
        error(source, status);
150
    }
151

    
152
    /**
153
     * Logs an exception from a given source as an error.
154
     *
155
     *
156
     * @param source
157
     *            a {@link java.lang.Class} object.
158
     * @param t
159
     *            a {@link java.lang.Throwable} object.
160
     */
161
    public static void error(Class<?> source, Throwable t) {
162
        error(source.getClass(), t.getMessage(), t);
163
    }
164

    
165
    /**
166
     * Returns a list of strings, providing info on,
167
     *  - login
168
     *  - editor version
169
     *  - server (address + source name)
170
     *  - db schema version
171
     *
172
     * @return
173
     */
174
    public static List<String> getContextInfo() {
175
        List<String> contextInfo = new ArrayList<>();
176
        String name = "";
177
        String contextPath = "";
178
        String schemaVersion = "";
179
        String server = "";
180
        String version = "";
181
        String login = "";
182
        try {
183
            version = Platform.getBundle("eu.etaxonomy.taxeditor.application").getHeaders().get(org.osgi.framework.Constants.BUNDLE_VERSION);
184

    
185
            ICdmSource activeCdmSource = CdmStore.getActiveCdmSource();
186
            if(activeCdmSource != null ) {
187
                login = CdmStore.getLoginManager().getAuthenticatedUser().getUsername();
188
                name = activeCdmSource.getName();
189
                schemaVersion = activeCdmSource.getDbSchemaVersion();
190
                server = activeCdmSource.getServer();
191
                if(activeCdmSource instanceof ICdmRemoteSource){
192
                    contextPath = ((ICdmRemoteSource)activeCdmSource).getContext();
193
                    if (contextPath != null && contextPath.startsWith("cdmserver/")){
194
                    	contextPath = contextPath.substring("cdmserver/".length());
195
                    }
196
                }
197
            }
198

    
199
        } catch (Exception e) {
200
            // Nothing to do
201
        }
202

    
203
        // add time stamps
204
        LocalDateTime date = LocalDateTime.now();
205
        String dateTimeStr = date.format(DateTimeFormatter.ISO_DATE_TIME);
206

    
207
        if(RemoteExecutionTimestampsUtil.getLastServiceMethod() != null){
208
            contextInfo.add("last remote method : " + RemoteExecutionTimestampsUtil.getLastServiceMethod());
209
        }
210
        if(RemoteExecutionTimestampsUtil.getLastRequestClientTime() != null){
211
            contextInfo.add("last remote request client time : " + RemoteExecutionTimestampsUtil.getLastRequestClientTime());
212
        }
213
        if(RemoteExecutionTimestampsUtil.getLastResponseHttpHeaderTime()!= null){
214
            contextInfo.add("last remote request response header time : " + RemoteExecutionTimestampsUtil.getLastResponseHttpHeaderTime());
215
        }
216
        contextInfo.add("client error time : " + dateTimeStr);
217
        contextInfo.add("login : " + login);
218
        contextInfo.add("editor version : " + version);
219
        contextInfo.add("server : " + server + " (" + name + ")" + (CdmUtils.isNotBlank(contextPath)?" / "+contextPath:""));
220
        contextInfo.add("schema version : " + schemaVersion);
221
        contextInfo.add("os : " + System.getProperty("os.name")+" "+System.getProperty("os.version")+" "+System.getProperty("os.arch"));
222
        contextInfo.add("java : "+System.getProperty("java.version"));
223

    
224
        return contextInfo;
225
    }
226

    
227
    public static String getStackTraceAndContextInfo(Throwable t, List<String> contextInfo)  {
228
        StringBuffer stackTraceAndContextInfo = new StringBuffer();
229
        Throwable throwable = t;
230

    
231
        for(String infoItem : contextInfo) {
232
            stackTraceAndContextInfo.append(infoItem + System.getProperty("line.separator"));
233
        }
234

    
235
        StringWriter sw = new StringWriter();
236

    
237
        if(throwable == null) {
238
            throwable = getDefaultThrowable();
239
        }
240
        throwable.printStackTrace(new PrintWriter(sw));
241

    
242
        stackTraceAndContextInfo.append(sw.toString());
243

    
244
        return stackTraceAndContextInfo.toString();
245
    }
246

    
247
    public static String getContextInfo(List<String> contextInfo)  {
248
        StringBuffer scontextInfoStringBuffer = new StringBuffer();
249

    
250
        for(String infoItem : contextInfo) {
251
            scontextInfoStringBuffer.append(infoItem + System.getProperty("line.separator"));
252
        }
253

    
254
        return scontextInfoStringBuffer.toString();
255
    }
256

    
257
    private static Throwable getDefaultThrowable() {
258
        return new Throwable("Error thrown but no associated exception");
259
    }
260

    
261
    /**
262
     * Displays a {@link eu.etaxonomy.taxeditor.model.CdmErrorDialog}.
263
     *
264
     */
265
    private static void errorDialog(final String title,
266
            final Object source,
267
            final Throwable t,
268
            final List<String> contextInfo,
269
            final String message,
270
            final MultiStatus status,
271
            final boolean showReason) {
272

    
273
        Display.getDefault().asyncExec(new Runnable() {
274

    
275
            @Override
276
            public void run() {
277
                String stackTraceWithContext = getStackTraceAndContextInfo(t, contextInfo);
278
                CdmErrorDialog ced = new CdmErrorDialog(AbstractUtility.getShell(), title, message, status, stackTraceWithContext, showReason);
279
                ced.open();
280
                Class<? extends Object> clazz = source != null ? source.getClass() : this.getClass();
281

    
282

    
283
                IStatus singleStatus = new Status(IStatus.ERROR,
284
                        status.getPlugin(),
285
                        message,
286
                        new Exception(stackTraceWithContext));
287

    
288
                error(clazz, singleStatus);
289
            }
290
        });
291
    }
292

    
293
    public static void errorDialog(final String title,
294
            final Object source,
295
            final String message,
296
            final String pluginId,
297
            final Throwable t,
298
            boolean addContactMesg) {
299
        errorDialog(title, source, message, pluginId, t, addContactMesg, true);
300

    
301
    }
302

    
303
    /**
304
     * Displays a {@link eu.etaxonomy.taxeditor.model.CdmErrorDialog}.
305
     */
306
    public static void errorDialog(final String title,
307
            final Object source,
308
            final String message,
309
            final String pluginId,
310
            final Throwable t,
311
            boolean addContactMesg,
312
            boolean showReason) {
313

    
314
        Throwable throwable = t;
315

    
316
        // We need to build a MultiStatus object since the simple
317
        // idea of writing out the stack trace as a single string
318
        // leads to a single line on windows
319
        List<Status> childStatuses = new ArrayList<>();
320

    
321
        // add context info
322
        List<String> contextInfo = getContextInfo();
323
        for(String infoItem : contextInfo) {
324
            childStatuses.add(new Status(IStatus.ERROR, pluginId, infoItem));
325
        }
326

    
327
        if(throwable == null) {
328
            throwable = getDefaultThrowable();
329
        }
330

    
331
        int thCount = 0;
332
        int maxTraces = 4;
333

    
334
        for(Throwable th : ExceptionUtils.getThrowables(throwable)) {
335
            // add main exception
336
            if(thCount == 0) {
337
                for (StackTraceElement ste : th.getStackTrace()) {
338
                    childStatuses.add(new Status(IStatus.ERROR, pluginId, "  at " + ste.toString()));
339
                }
340
            } else {
341
                // add recursive causes
342
                if(th != null) {
343
                    childStatuses.add(new Status(IStatus.ERROR, pluginId, ""));
344
                    String msg = th.toString();
345
                    childStatuses.add(new Status(IStatus.ERROR, pluginId, "Caused by : " + msg));
346
                    int traceCount = 0;
347
                    for (StackTraceElement ste : th.getStackTrace()) {
348
                        // add only pre-defined number of trace elements
349
                        if(traceCount > maxTraces) {
350
                            childStatuses.add(new Status(IStatus.ERROR, pluginId, "  ...."));
351
                            break;
352
                        }
353
                        // build & add status
354
                        childStatuses.add(new Status(IStatus.ERROR, pluginId, "  at " + ste.toString()));
355
                        traceCount++;
356
                    }
357
                }
358
            }
359
            thCount++;
360
        }
361
        String finalMessage = message;
362

    
363
        if(finalMessage == null || finalMessage.isEmpty()) {
364
            finalMessage = DEFAULT_MESSAGE;
365
        }
366

    
367
        if(addContactMesg) {
368
            // add edit support contact info to message
369
            finalMessage += MessagingUtils.CONTACT_MESSAGE;
370
        }
371

    
372
        MultiStatus ms = new MultiStatus(pluginId,
373
                IStatus.ERROR,
374
                childStatuses.toArray(new Status[] {}),
375
                throwable.toString(),
376
                throwable);
377

    
378
        errorDialog(title, source, throwable, contextInfo, finalMessage, ms, showReason);
379
    }
380

    
381
    /**
382
     * Displays a dialog for an exception occurring in an operation.
383
     *
384
     * This will be either a {@link eu.etaxonomy.taxeditor.model.CdmErrorDialog} in case of a
385
     * security runtime exception or a warning {@link org.eclipse.jface.dialogs.MessageDialog} in
386
     * case of any other exception.
387
     *
388
     * @param title
389
     *            a {@link java.lang.String} object.
390
     * @param source
391
     *            a {@link java.lang.Object} object.
392
     * @param status
393
     *            a {@link org.eclipse.core.runtime.IStatus} object.
394
     */
395
    public static void operationDialog(final Object source,
396
            final Exception ex,
397
            final String pluginId,
398
            final String operationlabel,
399
            final String hint) {
400

    
401
        Display.getDefault().asyncExec(new Runnable() {
402

    
403
            @Override
404
            public void run() {
405

    
406
                String title = null;
407

    
408
                // FIXME cannot access TaxonomicEditorPlugin.PLUGIN_ID from here
409
                // FIXME is there any reason for keeping the lines below?
410
                // String PID = TaxonomicEditorPlugin.PLUGIN_ID;
411
                // String PID = "eu.etaxonomy.taxeditor.application";
412

    
413
                // checking security exceptions for every operation
414
                RuntimeException securityRuntimeException = SecurityExceptionUtils.findSecurityRuntimeException(ex);
415

    
416
                // in case of a security exception it is a warning, else it is an error
417
                if(securityRuntimeException != null){
418
                    title = "Your changes could not be saved!";
419
                    warningDialog(title, source, String.format("You are missing sufficient permissions for the operation \"%s\". %s", operationlabel, hint));
420
                } else {
421
                    title = "Error executing operation";
422
                    errorDialog(title, source, String.format("An error occurred while executing %s. %s", operationlabel, hint), pluginId, ex, true);
423
                }
424
            }
425
        });
426
    }
427

    
428
    /**
429
     * Displays a question {@link org.eclipse.jface.dialogs.MessageDialog}.
430
     *
431
     * @param title
432
     *            a {@link java.lang.String} object.
433
     * @param message
434
     *            a {@link java.lang.String} object.
435
     * @return a boolean.
436
     */
437
    public static boolean confirmDialog(String title, String message) {
438
        return MessageDialog.openQuestion(AbstractUtility.getShell(), title, message);
439
    }
440

    
441
    public static int confirmDialog(String title, String message, String...labels){
442
        MessageDialog dialog =new MessageDialog(AbstractUtility.getShell(), title, null, message, MessageDialog.QUESTION,labels, 0);
443
        int result = dialog.open();
444
        return result;
445
    }
446

    
447
    /**
448
     * Displays a message {@link org.eclipse.jface.dialogs.MessageDialog}.
449
     *
450
     * @param title
451
     * @param source
452
     * @param message
453
     */
454
    public static void messageDialog(final String title, final Object source, final String message) {
455
        MessagingUtils.messageDialog(title, source, message, null, true);
456
    }
457

    
458
    /**
459
     * Displays an error {@link org.eclipse.jface.dialogs.MessageDialog}.
460
     *
461
     * @param title
462
     *            The dialogs title
463
     * @param source
464
     *            The object where the warning was generated (used by log4j)
465
     * @param message
466
     *            An informative String to be presented to the user
467
     * @param title
468
     *            The dialogs title
469
     * @param t
470
     *            a Throwable if one exists or null
471
     */
472
    public static void messageDialog(final String title,
473
            final Object source,
474
            final String message,
475
            final Throwable t) {
476
        MessagingUtils.messageDialog(title, source, message, t, true);
477
    }
478

    
479
    /**
480
     * Displays an error {@link org.eclipse.jface.dialogs.MessageDialog}.
481
     *
482
     * @param title
483
     *            The dialogs title
484
     * @param source
485
     *            The object where the warning was generated (used by log4j)
486
     * @param message
487
     *            An informative String to be presented to the user
488
     * @param title
489
     *            The dialogs title
490
     * @param t
491
     *            a Throwable if one exists or null
492
     */
493
    public static void messageDialog(final String title,
494
            final Object source,
495
            final String message,
496
            final Throwable t,
497
            boolean async) {
498
        if(async) {
499
            Display.getDefault().asyncExec(new Runnable() {
500

    
501
                @Override
502
                public void run() {
503
                    MessageDialog.openError(AbstractUtility.getShell(), title, message + getCauseRecursively(t));
504
                    Class<? extends Object> clazz = source != null ? source
505
                            .getClass() : this.getClass();
506
                            error(clazz, message, t);
507
                }
508

    
509

    
510
            });
511
        } else {
512
            MessageDialog.openError(AbstractUtility.getShell(), title, message + getCauseRecursively(t));
513
            Class<? extends Object> clazz = source != null ? source.getClass() : TaxeditorStorePlugin.class;
514
            error(clazz, message, t);
515
        }
516
    }
517

    
518
    public static String getCauseRecursively(Throwable t) {
519
        if(t == null){
520
            return "";
521
        }
522

    
523
        if(t.getCause() != null){
524
            return getCauseRecursively(t.getCause());
525
        }else{
526
            return String.format("\n\nException: %s\nMessage: %s", t.getClass().getSimpleName(), t.getMessage());
527
        }
528

    
529
    }
530

    
531
    /**
532
     * Displays a warning {@link org.eclipse.jface.dialogs.MessageDialog}.
533
     *
534
     * @param title
535
     * @param termBase
536
     * @param status
537
     */
538
    public static void warningDialog(String title, Object source,
539
            IStatus status) {
540
        MessagingUtils.warningDialog(title, source, status.getMessage());
541
    }
542

    
543
    /**
544
     * Standard warning dialog for the case when the application is not yet connected to the datasource.
545
     *
546
     * @param source
547
     */
548
    public static void noDataSourceWarningDialog(Object source) {
549
        MessagingUtils
550
        .warningDialog(
551
                "Application is not connected to a datastore",
552
                source,
553
                "The requested operation is only available when "
554
                + "connected to a datasource. You may choose a datasource to connect to or create a new one in the datasource view.");
555
    }
556

    
557
    /**
558
     * Standard warning dialog for the case when the datasource is not available
559
     *
560
     * @param source
561
     */
562
    public static void dataSourceNotAvailableWarningDialog(Object source) {
563
        MessagingUtils
564
        .warningDialog(
565
                "The datasource is not available",
566
                source,
567
                "The editor is not connected to a datasource. Maybe the datasource is not available.");
568
    }
569

    
570
    /**
571
     * Displays a warning {@link org.eclipse.jface.dialogs.MessageDialog}.
572
     *
573
     * @param title
574
     *            The dialogs title
575
     * @param source
576
     *            The object where the warning was generated (used by log4j)
577
     * @param message
578
     *            An informative String to be presented to the user
579
     */
580
    public static void warningDialog(final String title, final Object source, final String message) {
581
        Display.getDefault().asyncExec(new Runnable() {
582

    
583
            @Override
584
            public void run() {
585
                MessageDialog.openWarning(AbstractUtility.getShell(), title, message);
586
                Class<? extends Object> clazz = source != null ? source
587
                        .getClass() : AbstractUtility.class;
588
                        warn(clazz, message);
589
            }
590
        });
591
    }
592

    
593
    /**
594
     * Displays an information {@link org.eclipse.jface.dialogs.MessageDialog}.
595
     */
596
    public static void informationDialog(final String title, final IStatus status) {
597
        MessagingUtils.informationDialog(title, status.getMessage());
598
    }
599

    
600
    /**
601
     * Displays an information {@link org.eclipse.jface.dialogs.MessageDialog}.
602
     *
603
     * @param title
604
     *            a {@link java.lang.String} object.
605
     * @param message
606
     *            a {@link java.lang.String} object.
607
     */
608
    public static void informationDialog(final String title,
609
            final String message) {
610
        Display.getDefault().asyncExec(new Runnable() {
611

    
612
            @Override
613
            public void run() {
614
                MessageDialog.openInformation(AbstractUtility.getShell(), title, message);
615
            }
616
        });
617
    }
618

    
619
    /**
620
     * Open a message box that informs the user about unimplemented
621
     * functionality. This method is for developer convenience.
622
     *
623
     * @param source
624
     *            a {@link java.lang.Object} object.
625
     */
626
    public static void notImplementedMessage(Object source) {
627
        warningDialog("Not yet implemented", source,
628
                "This functionality is not yet implemented.");
629
    }
630

    
631
}
(31-31/40)