Project

General

Profile

Download (48.5 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2015 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
package eu.etaxonomy.taxeditor.ui.dialog;
10

    
11
import java.io.File;
12
import java.io.IOException;
13
import java.text.SimpleDateFormat;
14
import java.util.Date;
15
import java.util.HashMap;
16
import java.util.List;
17
import java.util.Map;
18

    
19
import org.apache.commons.lang.StringUtils;
20
import org.apache.log4j.Logger;
21
import org.eclipse.core.runtime.IProgressMonitor;
22
import org.eclipse.core.runtime.IStatus;
23
import org.eclipse.core.runtime.Status;
24
import org.eclipse.core.runtime.jobs.Job;
25
import org.eclipse.core.runtime.preferences.ConfigurationScope;
26
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
27
import org.eclipse.jface.layout.GridDataFactory;
28
import org.eclipse.swt.SWT;
29
import org.eclipse.swt.SWTException;
30
import org.eclipse.swt.custom.StyledText;
31
import org.eclipse.swt.events.KeyAdapter;
32
import org.eclipse.swt.events.KeyEvent;
33
import org.eclipse.swt.events.MouseAdapter;
34
import org.eclipse.swt.events.MouseEvent;
35
import org.eclipse.swt.events.SelectionAdapter;
36
import org.eclipse.swt.events.SelectionEvent;
37
import org.eclipse.swt.graphics.Point;
38
import org.eclipse.swt.layout.FillLayout;
39
import org.eclipse.swt.layout.GridData;
40
import org.eclipse.swt.layout.GridLayout;
41
import org.eclipse.swt.widgets.Button;
42
import org.eclipse.swt.widgets.Combo;
43
import org.eclipse.swt.widgets.Composite;
44
import org.eclipse.swt.widgets.Dialog;
45
import org.eclipse.swt.widgets.Display;
46
import org.eclipse.swt.widgets.Label;
47
import org.eclipse.swt.widgets.Shell;
48
import org.eclipse.swt.widgets.Text;
49
import org.eclipse.ui.forms.events.ExpansionEvent;
50
import org.eclipse.ui.forms.events.IExpansionListener;
51
import org.eclipse.ui.forms.widgets.ExpandableComposite;
52
import org.eclipse.ui.progress.IProgressConstants;
53
import org.eclipse.wb.swt.SWTResourceManager;
54
import org.osgi.service.prefs.BackingStoreException;
55
import org.osgi.service.prefs.Preferences;
56
import org.springframework.security.authentication.BadCredentialsException;
57
import org.springframework.security.authentication.LockedException;
58
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
59

    
60
import eu.etaxonomy.cdm.api.application.CdmApplicationRemoteConfiguration;
61
import eu.etaxonomy.cdm.api.application.CdmApplicationState;
62
import eu.etaxonomy.cdm.api.service.IUserService;
63
import eu.etaxonomy.cdm.model.metadata.CdmMetaData;
64
import eu.etaxonomy.cdm.persistence.hibernate.permission.Role;
65
import eu.etaxonomy.taxeditor.l10n.Messages;
66
import eu.etaxonomy.taxeditor.model.MessagingUtils;
67
import eu.etaxonomy.taxeditor.preference.IPreferenceKeys;
68
import eu.etaxonomy.taxeditor.preference.PreferencesUtil;
69
import eu.etaxonomy.taxeditor.remoting.server.CDMServerException;
70
import eu.etaxonomy.taxeditor.remoting.server.CDMServerUtils;
71
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
72
import eu.etaxonomy.taxeditor.remoting.source.CdmServerInfo;
73
import eu.etaxonomy.taxeditor.remoting.source.CdmServerInfo.CdmInstanceInfo;
74
import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
75
import eu.etaxonomy.taxeditor.store.CdmStore;
76
import eu.etaxonomy.taxeditor.store.LoginManager;
77
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
78
import eu.etaxonomy.taxeditor.webapp.CDMEmbeddedServerException;
79
import eu.etaxonomy.taxeditor.webapp.CDMServer;
80
import eu.etaxonomy.taxeditor.webapp.ICDMServerError;
81

    
82

    
83
/**
84
 * @author cmathew
85
 * @date 20 Jan 2015
86
 *
87
 */
88
public class RemotingLoginDialog extends Dialog implements ICDMServerError {
89

    
90
    private Logger logger = Logger.getLogger(getClass());
91

    
92
    private static final String DEFAULT_PASS = "00000"; //$NON-NLS-1$
93
    private static final String DEFAULT_USER = "admin"; //$NON-NLS-1$
94
    private static final String UBUNTU = "Ubuntu"; //$NON-NLS-1$
95
	protected Object result;
96
    protected Shell shlConnect;
97
    private Text txtCdmServerStatus;
98
    private Text txtCdmInstanceStatus;
99
    private Combo comboCdmServer;
100
    private Combo comboCdmInstance;
101
    private Button btnConnect;
102

    
103
    private final Map<String, CdmServerInfo> csiiMap = new HashMap<String, CdmServerInfo>();
104

    
105
    private final static String STATUS_AVAILABLE = Messages.RemotingLoginDialog_STATUS_AVAILABLE;
106
    private final static String STATUS_NOT_AVAILABLE = Messages.RemotingLoginDialog_STATUS_NOT_AVAILABLE;
107
    private final static String STATUS_STARTED = Messages.RemotingLoginDialog_STATUS_STARTED;
108
    private final static String STATUS_NOT_STARTED = Messages.RemotingLoginDialog_STATUS_NOT_STARTED;
109
    private final static String STATUS_RETRIEVING = Messages.RemotingLoginDialog_STATUS_RETRIEVING;
110
    private final static String STATUS_CHECKING_AVAILABILITY = Messages.RemotingLoginDialog_STATUS_CHECKING;
111
    private final static String STATUS_NO_INSTANCES = Messages.RemotingLoginDialog_STATUS_NO_INSTANCES_FOUND;
112
    private final static String STATUS_NOT_COMPATIBLE = Messages.RemotingLoginDialog_STATUS_NOT_COMPATIBLE;
113

    
114
    private final static String MESG_COMPATIBLE_EDITOR_OLD = Messages.RemotingLoginDialog_UPDATE_EDITOR;
115
    private final static String MESG_COMPATIBLE_SERVER_OLD = Messages.RemotingLoginDialog_CHOOSE_COMPATIBLE_CDM_SERVER;
116

    
117
    private final static String STORE_PREFERENCES_NODE = "eu.etaxonomy.taxeditor.store"; //$NON-NLS-1$
118

    
119
    private final static String LOGIN_NODE = "login"; //$NON-NLS-1$
120
    private final static String USERNAME_SUFFIX = "_username"; //$NON-NLS-1$
121
    private final static String PASSWORD_SUFFIX = "_password"; //$NON-NLS-1$
122

    
123
    private final static String LAST_SERVER_INSTANCE_NODE = "lastServerInstance"; //$NON-NLS-1$
124
    private final static String LAST_SERVER_KEY = "lastServerKey"; //$NON-NLS-1$
125
    private final static String LAST_INSTANCE_KEY = "lastInstanceKey"; //$NON-NLS-1$
126

    
127

    
128
    private Composite remotingComposite;
129
    private CdmServerInfo selectedCsii;
130
    private CdmInstanceInfo selectedCdmInstance;
131
    private Button btnCdmServerRefresh;
132
    private Button btnCdmInstanceRefresh;
133
    private Button btnStopServer;
134
    private Composite loginComposite;
135
    private Label lblLogin;
136
    private Text txtLogin;
137
    private Label lblPassword;
138
    private Text txtPassword;
139
    private Button btnRememberMe;
140
    private Composite compAdvanced;
141
    private Label lblPort;
142
    private Text txtPort;
143
    private Label lblServerVersion;
144
    private Text txtServerVersion;
145
    private ExpandableComposite xpndblcmpstAdvanced;
146
    private StyledText styledTxtMessage;
147

    
148

    
149
    private final int MIN_WIDTH = 530;
150
    private final int MIN_HEIGHT = 220;
151
    private final int MIN_EXP_HEIGHT = 380;
152
    private final int MESSAGE_HEIGHT = 50;
153
    private Label lblEditorVersion;
154
    private Text txtEditorVersion;
155
    private Label lblServerCDMVersion;
156
    private Text txtServerCDMVersion;
157
    private Label lblEditorCDMVersion;
158
    private Text txtEditorCDMVersion;
159

    
160
    private String serverName, instanceName;
161
    private boolean autoConnect = false;
162
    private boolean loadLoginPrefs = true;
163
    private boolean isDevRemoteSource = false;
164
    private Job serverJob;
165
    /**
166
     * Create the dialog.
167
     * @param parent
168
     * @param style
169
     */
170
    public RemotingLoginDialog(Shell parent, int style) {
171
        super(parent, style);
172
        setText(Messages.RemotingLoginDialog_LABEL_LOGIN);
173
    }
174

    
175
    public Object open(CdmRemoteSource source, boolean loadLoginPrefs, boolean autoConnect) {
176
        this.loadLoginPrefs = loadLoginPrefs;
177
        this.serverName = source.getName();
178
        String contextPath = source.getContextPath();
179
        this.instanceName = contextPath.substring(contextPath.lastIndexOf("/") + 1); //$NON-NLS-1$
180
        return open(serverName, instanceName, loadLoginPrefs, autoConnect);
181
    }
182

    
183

    
184
    public Object open(String serverName, String instanceName, boolean loadLoginPrefs, boolean autoConnect) {
185
        this.serverName = serverName;
186
        this.instanceName = instanceName;
187
        this.loadLoginPrefs = loadLoginPrefs;
188
        this.autoConnect = autoConnect;
189
        return open();
190
    }
191

    
192
    /**
193
     * Open the dialog.
194
     * @return the result
195
     */
196
    public Object open() {
197

    
198
        createContents();
199
        if(serverName == null && instanceName == null) {
200
            readPrefLastServerInstance();
201
        }
202

    
203
        setEditorInfo();
204
        populateCdmServerCombo();
205
        shlConnect.open();
206
        shlConnect.layout();
207

    
208
        xpndblcmpstAdvanced.setExpanded(false);
209

    
210
        Display display = getParent().getDisplay();
211

    
212
        while (!shlConnect.isDisposed()) {
213
            if (!display.isDisposed()){
214
                if (!display.readAndDispatch()) {
215
                    display.sleep();
216
                }
217
            }
218
        }
219

    
220
        return result;
221
    }
222

    
223
    /**
224
     * Create contents of the dialog.
225
     */
226
    private void createContents() {
227
        shlConnect = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
228
        shlConnect.setMinimumSize(new Point(MIN_WIDTH, MIN_HEIGHT));
229
        shlConnect.setSize(MIN_WIDTH, MIN_HEIGHT);
230
        shlConnect.setText(Messages.RemotingLoginDialog_LABEL_CONNECT);
231
        shlConnect.setLayout(new FillLayout(SWT.HORIZONTAL));
232

    
233
        remotingComposite = new Composite(shlConnect, SWT.NONE);
234
        remotingComposite.setLayout(new GridLayout(1, false));
235

    
236
        Composite cdmServerComposite = new Composite(remotingComposite, SWT.NONE);
237
        GridData gd_cdmServerComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
238
        gd_cdmServerComposite.heightHint = 68;
239
        cdmServerComposite.setLayoutData(gd_cdmServerComposite);
240
        cdmServerComposite.setLayout(new GridLayout(4, false));
241

    
242
        Label lblCdmServer = new Label(cdmServerComposite, SWT.NONE);
243
        lblCdmServer.setText(Messages.RemotingLoginDialog_LABEL_CDM_SERVER);
244
        lblCdmServer.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
245
        lblCdmServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
246

    
247
        comboCdmServer = new Combo(cdmServerComposite, SWT.READ_ONLY);
248
        comboCdmServer.addSelectionListener(new SelectionAdapter() {
249
            @Override
250
            public void widgetSelected(SelectionEvent e) {
251
                refreshCdmServer();
252

    
253
            }
254
        });
255
        GridData gd_comboCdmServer = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
256
        gd_comboCdmServer.widthHint = 150;
257
        comboCdmServer.setLayoutData(gd_comboCdmServer);
258
        comboCdmServer.select(0);
259

    
260
        txtCdmServerStatus = new Text(cdmServerComposite, SWT.BORDER);
261
        txtCdmServerStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
262
        txtCdmServerStatus.setEditable(false);
263
        GridData gd_txtCdmServerStatus = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
264
        gd_txtCdmServerStatus.widthHint = 100;
265

    
266
        txtCdmServerStatus.setLayoutData(gd_txtCdmServerStatus);
267

    
268
        btnCdmServerRefresh = new Button(cdmServerComposite, SWT.NONE);
269
        btnCdmServerRefresh.addSelectionListener(new SelectionAdapter() {
270
            @Override
271
            public void widgetSelected(SelectionEvent e) {
272
                refreshCdmServer();
273
            }
274
        });
275
        btnCdmServerRefresh.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
276
        btnCdmServerRefresh.setText(Messages.RemotingLoginDialog_LABEL_REFRESH);
277

    
278
        Label lblCdmInstance = new Label(cdmServerComposite, SWT.NONE);
279
        GridData gd_lblCdmInstance = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
280
        gd_lblCdmInstance.heightHint = 30;
281
        lblCdmInstance.setLayoutData(gd_lblCdmInstance);
282
        lblCdmInstance.setText(Messages.RemotingLoginDialog_LABEL_CDM_INSTANCE);
283
        lblCdmInstance.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
284

    
285
        comboCdmInstance = new Combo(cdmServerComposite, SWT.READ_ONLY);
286
        comboCdmInstance.addSelectionListener(new SelectionAdapter() {
287
            @Override
288
            public void widgetSelected(SelectionEvent e) {
289
                refreshCdmInstance();
290
            }
291
        });
292
        GridData gd_comboCdmInstance = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
293
        gd_comboCdmInstance.widthHint = 150;
294
        comboCdmInstance.setLayoutData(gd_comboCdmInstance);
295
        comboCdmInstance.select(0);
296

    
297
        txtCdmInstanceStatus = new Text(cdmServerComposite, SWT.BORDER);
298
        txtCdmInstanceStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
299
        txtCdmInstanceStatus.setEditable(false);
300
        GridData gd_txtCdmInstanceStatus = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
301
        gd_txtCdmInstanceStatus.widthHint = 100;
302
        txtCdmInstanceStatus.setLayoutData(gd_txtCdmInstanceStatus);
303

    
304
        btnCdmInstanceRefresh = new Button(cdmServerComposite, SWT.FLAT);
305
        btnCdmInstanceRefresh.addSelectionListener(new SelectionAdapter() {
306
            @Override
307
            public void widgetSelected(SelectionEvent e) {
308
                refreshCdmInstance();
309
            }
310
        });
311
        GridData gd_btnCdmInstanceRefresh = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
312
        gd_btnCdmInstanceRefresh.widthHint = 110;
313
        gd_btnCdmInstanceRefresh.heightHint = 30;
314
        btnCdmInstanceRefresh.setLayoutData(gd_btnCdmInstanceRefresh);
315
        btnCdmInstanceRefresh.setText(Messages.RemotingLoginDialog_LABEL_REFRESH);
316

    
317
        loginComposite = new Composite(remotingComposite, SWT.NONE);
318
        GridData gd_loginComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
319
        gd_loginComposite.widthHint = 487;
320
        gd_loginComposite.heightHint = 70;
321
        loginComposite.setLayoutData(gd_loginComposite);
322
        GridLayout gl_loginComposite = new GridLayout(6, false);
323
        gl_loginComposite.marginTop = 5;
324
        loginComposite.setLayout(gl_loginComposite);
325

    
326
        lblLogin = new Label(loginComposite, SWT.CENTER);
327
        GridData gd_lblLogin = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
328
        gd_lblLogin.widthHint = 50;
329
        lblLogin.setLayoutData(gd_lblLogin);
330
        lblLogin.setText(Messages.RemotingLoginDialog_LABEL_LOGIN_COLON);
331
        lblLogin.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
332

    
333
        txtLogin = new Text(loginComposite, SWT.BORDER);
334
        GridData gd_txtLogin = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
335
        gd_txtLogin.minimumWidth = 80;
336
        gd_txtLogin.widthHint = 80;
337
        gd_txtLogin.heightHint = 15;
338
        txtLogin.setLayoutData(gd_txtLogin);
339

    
340
        lblPassword = new Label(loginComposite, SWT.CENTER);
341
        lblPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
342
        lblPassword.setText(Messages.RemotingLoginDialog_LABEL_PASSWORD);
343
        lblPassword.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
344

    
345
        txtPassword = new Text(loginComposite, SWT.BORDER | SWT.PASSWORD);
346
        GridData gd_txtPassword = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
347
        gd_txtPassword.minimumWidth = 80;
348
        gd_txtPassword.widthHint = 80;
349
        gd_txtPassword.heightHint = 15;
350
        txtPassword.setLayoutData(gd_txtPassword);
351
        new Label(loginComposite, SWT.NONE);
352
        txtPassword.addKeyListener(new KeyAdapter() {
353
        	@Override
354
        	public void keyPressed(KeyEvent e) {
355
        		if(e.character==SWT.CR){
356
        			connectButtonPressed();
357
        		}
358
        	}
359
        });
360

    
361
        btnConnect = new Button(loginComposite, SWT.FLAT);
362
        btnConnect.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
363
        btnConnect.addSelectionListener(new SelectionAdapter() {
364
			@Override
365
			public void widgetSelected(SelectionEvent e) {
366
				connectButtonPressed();
367
			}
368
		});
369
        btnConnect.setText(Messages.RemotingLoginDialog_LABEL_CONNECT);
370

    
371
        btnRememberMe = new Button(loginComposite, SWT.CHECK);
372
        btnRememberMe.setSelection(true);
373
        GridData gd_btnRememberMe = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1);
374
        btnRememberMe.setLayoutData(gd_btnRememberMe);
375
        btnRememberMe.setText(Messages.RemotingLoginDialog_LABEL_REMEMBER_ME);
376

    
377
        Label lblDefaultLogin = new Label(loginComposite, SWT.NONE);
378
        GridDataFactory.fillDefaults().span(4, 1).align(SWT.TRAIL, SWT.CENTER).applyTo(lblDefaultLogin);
379
        lblDefaultLogin.setText(String.format(Messages.RemotingLoginDialog_DEFAULT_LOGIN, DEFAULT_USER, DEFAULT_PASS));
380

    
381
        styledTxtMessage = new StyledText(remotingComposite, SWT.NONE);
382
        styledTxtMessage.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
383
        styledTxtMessage.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
384
        styledTxtMessage.setFont(SWTResourceManager.getFont(UBUNTU, 12, SWT.BOLD));
385
        styledTxtMessage.setSelectionBackground(SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION_TEXT));
386
        styledTxtMessage.setSelectionForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
387
        styledTxtMessage.setDoubleClickEnabled(false);
388
        styledTxtMessage.setEditable(false);
389
        styledTxtMessage.setWordWrap(true);
390

    
391
        GridData gd_styledTxtMessage = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
392
        gd_styledTxtMessage.exclude = true;
393
        gd_styledTxtMessage.minimumHeight = MESSAGE_HEIGHT;
394
        gd_styledTxtMessage.heightHint = MESSAGE_HEIGHT;
395
        gd_styledTxtMessage.widthHint = MIN_WIDTH - 5;
396

    
397
        styledTxtMessage.setLayoutData(gd_styledTxtMessage);
398

    
399
        xpndblcmpstAdvanced = new ExpandableComposite(remotingComposite, SWT.NONE, ExpandableComposite.TWISTIE);
400
        GridData gd_xpndblcmpstAdvanced = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1);
401
        gd_xpndblcmpstAdvanced.heightHint = 19;
402
        gd_xpndblcmpstAdvanced.widthHint = MIN_WIDTH - 10;
403
        xpndblcmpstAdvanced.setLayoutData(gd_xpndblcmpstAdvanced);
404
        xpndblcmpstAdvanced.addExpansionListener(new IExpansionListener() {
405
            @Override
406
            public void expansionStateChanged(ExpansionEvent e) {
407
                if(e.getState()) {
408
                    shlConnect.setSize(MIN_WIDTH, MIN_EXP_HEIGHT);
409
                } else {
410
                    shlConnect.setSize(MIN_WIDTH, MIN_HEIGHT);
411
                }
412

    
413
            }
414
            @Override
415
            public void expansionStateChanging(ExpansionEvent e) {
416
            }
417
        });
418
        xpndblcmpstAdvanced.setText(Messages.RemotingLoginDialog_LABEL_ADVANCED);
419
        xpndblcmpstAdvanced.setExpanded(true);
420

    
421
        compAdvanced = new Composite(xpndblcmpstAdvanced, SWT.NONE);
422
        xpndblcmpstAdvanced.setClient(compAdvanced);
423
        compAdvanced.setLayout(new GridLayout(4, false));
424

    
425
        lblPort = new Label(compAdvanced, SWT.CENTER);
426
        lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
427
        lblPort.setSize(0, 0);
428
        lblPort.setText(Messages.RemotingLoginDialog_LABEL_PORT);
429
        lblPort.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
430

    
431
        txtPort = new Text(compAdvanced, SWT.BORDER);
432
        GridData gd_txtPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
433
        gd_txtPort.minimumWidth = 50;
434
        gd_txtPort.widthHint = 50;
435
        txtPort.setLayoutData(gd_txtPort);
436

    
437
        lblServerVersion = new Label(compAdvanced, SWT.CENTER);
438
        lblServerVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
439
        lblServerVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDMLIB_VERSION);
440
        lblServerVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
441

    
442
        txtServerVersion = new Text(compAdvanced, SWT.BORDER);
443
        txtServerVersion.setEditable(false);
444
        txtServerVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
445
        btnStopServer = new Button(compAdvanced, SWT.FLAT);
446
        btnStopServer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
447
        btnStopServer.addMouseListener(new MouseAdapter() {
448
            @Override
449
            public void mouseUp(MouseEvent e) {
450
                stopManagedServer();
451
            }
452
        });
453
        btnStopServer.setText(Messages.RemotingLoginDialog_LABEL_STOP_MANAGED_SERVER);
454

    
455
        lblEditorVersion = new Label(compAdvanced, SWT.CENTER);
456
        lblEditorVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
457
        lblEditorVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDMLIB_VERSION);
458
        lblEditorVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
459

    
460
        txtEditorVersion = new Text(compAdvanced, SWT.BORDER);
461
        txtEditorVersion.setEditable(false);
462
        txtEditorVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
463
        new Label(compAdvanced, SWT.NONE);
464
        new Label(compAdvanced, SWT.NONE);
465

    
466
        lblServerCDMVersion = new Label(compAdvanced, SWT.CENTER);
467
        lblServerCDMVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
468
        lblServerCDMVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDM_VERSION);
469
        lblServerCDMVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
470

    
471
        txtServerCDMVersion = new Text(compAdvanced, SWT.BORDER);
472
        txtServerCDMVersion.setEditable(false);
473
        txtServerCDMVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
474
        new Label(compAdvanced, SWT.NONE);
475
        new Label(compAdvanced, SWT.NONE);
476

    
477
        lblEditorCDMVersion = new Label(compAdvanced, SWT.CENTER);
478
        lblEditorCDMVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
479
        lblEditorCDMVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDM_VERSION);
480
        lblEditorCDMVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
481

    
482
        txtEditorCDMVersion = new Text(compAdvanced, SWT.BORDER);
483
        txtEditorCDMVersion.setEditable(false);
484
        txtEditorCDMVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
485

    
486
    }
487

    
488
	private void connectButtonPressed() {
489
		if(selectedCsii.isLocalhostMgd() && !isSelectedCdmInstanceRunningInManagedServer()) {
490
			startManagedServer();
491
		} else {
492
			connect();
493
			if (CdmStore.isActive() && CdmStore.currentAuthentiationHasOneOfRoles(Role.ROLE_REMOTING)){
494
			    PreferencesUtil.setNomenclaturalCodePreferences();
495
			}
496

    
497
		}
498
	}
499

    
500
    private void populateCdmServerCombo() {
501
        Job job = new Job(Messages.RemotingLoginDialog_RETRIEVE_SERVER_INSTANCES) {
502
            @Override
503
            protected IStatus run(IProgressMonitor monitor) {
504
                Display.getDefault().syncExec(new Runnable() {
505
                    @Override
506
                    public void run() {
507
                        for(CdmServerInfo csii : CdmServerInfo.getCdmServers()) {
508
                            csiiMap.put(csii.getName(), csii);
509
                            comboCdmServer.add(csii.getName());
510
                        }
511
                        int serverIndex = -1;
512
                        if(serverName != null) {
513
                            serverIndex = comboCdmServer.indexOf(serverName);
514
                        }
515
                        if(serverIndex == -1) {
516
                            comboCdmServer.select(0);
517
                            autoConnect = false;
518
                        } else {
519
                            comboCdmServer.select(serverIndex);
520
                        }
521
                        CdmRemoteSource devRemoteSource = CdmServerInfo.getDevServerRemoteSource();
522
                        if(devRemoteSource != null) {
523
                            isDevRemoteSource = true;
524
                            String username = System.getProperty("cdm.server.dev.username"); //$NON-NLS-1$
525
                            String password = System.getProperty("cdm.server.dev.password"); //$NON-NLS-1$
526
                            if(username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
527
                                txtLogin.setText(username);
528
                                txtPassword.setText(password);
529
                                CdmStore.connect(devRemoteSource, RemotingLoginDialog.this);
530
                            }
531
                        } else {
532
                            refreshCdmServer();
533
                        }
534
                    }
535
                });
536
                return Status.OK_STATUS;
537
            }
538
        };
539
        job.schedule();
540
    }
541

    
542

    
543
    private void refreshCdmServer() {
544
        try{
545
            txtCdmServerStatus.setText(STATUS_CHECKING_AVAILABILITY);
546
            clearOnServerChange();
547
            emptyCredentials();
548
            updateSelectedCdmServer();
549
            Display.getDefault().asyncExec(new Runnable() {
550
                @Override
551
                public void run() {
552
                    checkSelectedCdmServer();
553
                }
554
            });
555
        }
556
        catch(SWTException e){
557
            //catch widget is disposed exception which may occurr if
558
            //dialog is closed but the runnable tries to update
559
        }
560
    }
561

    
562
    private void updateSelectedCdmServer() {
563
        int selIndex = comboCdmServer.getSelectionIndex();
564
        if(selIndex != -1) {
565
            selectedCsii = csiiMap.get(comboCdmServer.getItem(selIndex));
566
        }
567
    }
568

    
569
    private void updatePort() {
570
        txtPort.setText(""); //$NON-NLS-1$
571
        if(selectedCsii != null) {
572
            int port = selectedCsii.getPort();
573
            if(port == CdmServerInfo.NULL_PORT) {
574
                txtPort.setText(CdmServerInfo.NULL_PORT_STRING);
575
            } else {
576
                txtPort.setText(String.valueOf(port));
577
            }
578
        }
579
    }
580

    
581
    private int getPort() {
582
        int port = CdmServerInfo.NULL_PORT;
583
        try {
584
            port = Integer.valueOf(txtPort.getText());
585
        } catch (NumberFormatException nfe) {
586
            if(!CdmServerInfo.NULL_PORT_STRING.equals(txtPort.getText())) {
587
                setMessage(Messages.RemotingLoginDialog_MESSAGE_PORT_SHOULD_BE_INTEGER);
588
            }
589
        }
590
        return port;
591
    }
592

    
593
    private void checkSelectedCdmServer() {
594
        try{
595
            if(selectedCsii != null) {
596
                if(selectedCsii.isLocalhost()) {
597
                    txtPort.setEditable(true);
598
                    txtPort.setEnabled(true);
599
                }
600
                try {
601
                    if(selectedCsii.pingServer()) {
602
                        txtCdmServerStatus.setText(STATUS_AVAILABLE);
603
                        populateCdmInstanceCombo(true);
604
                        String serverVersionTimestamp = generateLastModifiedTooltip(selectedCsii.getCdmlibLastModified());
605
                        txtServerVersion.setText(selectedCsii.getCdmlibServicesVersion() + ":" + serverVersionTimestamp); //$NON-NLS-1$
606
                    } else {
607
                        txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
608
                        comboCdmInstance.removeAll();
609
                        disableCdmInstanceControls("", ""); //$NON-NLS-1$ //$NON-NLS-2$
610
                    }
611
                } catch (CDMServerException | IOException e) {
612
                    txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
613
                    MessagingUtils.warningDialog(Messages.RemotingLoginDialog_CONNECTION_FAILED_TITLE, this,
614
                            Messages.RemotingLoginDialog_CONNECTION_FAILED_MESSAGE);
615
                    logger.warn(Messages.RemotingLoginDialog_CONNECTION_FAILED_TITLE, e);
616
                }
617
            }
618
            updatePort();
619
        }
620
        catch(SWTException e){
621
            //catch widget is disposed exception which may occurr if
622
            //dialog is closed but the runnable tries to update
623
        }
624
    }
625

    
626

    
627
    private void populateCdmInstanceCombo(final boolean forceRefresh) {
628
        comboCdmInstance.removeAll();
629
        comboCdmInstance.setEnabled(false);
630
        btnConnect.setEnabled(false);
631
        txtCdmInstanceStatus.setText(STATUS_RETRIEVING);
632
        txtCdmInstanceStatus.setToolTipText(""); //$NON-NLS-1$
633

    
634
        serverJob = new Job(Messages.RemotingLoginDialog_RETRIEVE_SERVER_INSTANCES) {
635
            @Override
636
            protected IStatus run(IProgressMonitor monitor) {
637
                try {
638
                    if(selectedCsii != null) {
639
                        if(forceRefresh) {
640
                            selectedCsii.refreshInstances();
641
                        }
642
                        final List<CdmInstanceInfo> instances = selectedCsii.getInstances();
643
                        Display.getDefault().asyncExec(new Runnable() {
644
                            @Override
645
                            public void run() {
646
                                if(!instances.isEmpty()) {
647
                                    for(CdmInstanceInfo cdmInstance : instances) {
648
                                        comboCdmInstance.add(cdmInstance.getName());
649
                                    }
650
                                    int instanceIndex = -1;
651
                                    if(instanceName != null) {
652
                                        instanceIndex = comboCdmInstance.indexOf(instanceName);
653
                                    }
654
                                    if(instanceIndex == -1) {
655
                                        comboCdmInstance.select(0);
656
                                        autoConnect = false;
657
                                    } else {
658
                                        comboCdmInstance.select(instanceIndex);
659
                                    }
660
                                    refreshCdmInstance();
661
                                    comboCdmInstance.setEnabled(true);
662
                                    if(autoConnect) {
663
                                        connect();
664
                                    }
665

    
666
                                } else {
667
                                    txtCdmInstanceStatus.setText(STATUS_NO_INSTANCES);
668
                                    btnConnect.setEnabled(false);
669
                                }
670
                            }
671
                        });
672
                    }
673
                } catch (final CDMServerException e) {
674
                    MessagingUtils.warn(getClass(), e);
675
                    Display.getDefault().asyncExec(new Runnable() {
676
                        @Override
677
                        public void run() {
678
                            disableCdmInstanceControls(STATUS_NOT_AVAILABLE, e.getMessage());
679
                        }
680
                    });
681
                }
682
                return Status.OK_STATUS;
683
            }
684
        };
685

    
686
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE) && !isDevRemoteSource) {
687
            // Start the Job
688
            serverJob.schedule();
689
        }
690
    }
691

    
692
    private void disableCdmInstanceControls(String cdmInstanceStatus, String tooltip) {
693
        txtCdmInstanceStatus.setText(cdmInstanceStatus);
694
        txtCdmInstanceStatus.setToolTipText(tooltip);
695
        comboCdmInstance.setEnabled(false);
696
        btnConnect.setEnabled(false);
697

    
698
    }
699
    private void refreshCdmInstance() {
700
        txtCdmInstanceStatus.setText(STATUS_CHECKING_AVAILABILITY);
701
        clearOnInstanceChange();
702
        updateSelectedCdmInstance();
703
        checkSelectedCdmInstance();
704
        updateManagedServerControls();
705
    }
706

    
707
    private void updateSelectedCdmInstance() {
708
        int selIndex = comboCdmInstance.getSelectionIndex();
709
        if(selIndex != -1) {
710
            selectedCdmInstance = selectedCsii.getInstanceFromName(comboCdmInstance.getItem(selIndex));
711

    
712
            if(loadLoginPrefs) {
713
                readPrefCredentials();
714
            }
715
        }
716
    }
717

    
718
    private void updateManagedServerControls() {
719
        if(selectedCsii.isLocalhostMgd()) {
720
            if(isSelectedCdmInstanceRunningInManagedServer()) {
721
                txtCdmInstanceStatus.setText(STATUS_STARTED);
722
            } else {
723
                txtCdmInstanceStatus.setText(STATUS_NOT_STARTED);
724
            }
725
            btnConnect.setEnabled(true);
726
            selectedCsii.setPort(getManagedServerPort());
727
            updatePort();
728
        }
729

    
730

    
731
        if(isManagedServerRunning()) {
732
            btnStopServer.setEnabled(true);
733
        } else {
734
            btnStopServer.setEnabled(false);
735
        }
736
    }
737

    
738
    private boolean isManagedServerRunning() {
739
        return CdmStore.getManagedServer() != null && CdmStore.getManagedServer().isAlive();
740
    }
741

    
742
    private boolean isSelectedCdmInstanceRunningInManagedServer() {
743
        return CdmStore.getManagedServer() != null &&
744
                CdmStore.getManagedServer().isAlive() &&
745
                selectedCsii.isLocalhostMgd() &&
746
                CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName());
747
    }
748

    
749
    private void startManagedServer() {
750
        if(isManagedServerRunning()) {
751
            if(CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())) {
752
                return;
753
            } else {
754
                Display.getDefault().syncExec(new Runnable() {
755
                    @Override
756
                    public void run() {
757
                        stopManagedServer();
758
                    }
759
                });
760
            }
761
        }
762

    
763

    
764
        Job job = new Job(Messages.RemotingLoginDialog_JOB_SERVER_LAUNCH) {
765

    
766
            @Override
767
            public IStatus run(IProgressMonitor monitor) {
768
                String mgdServerConfigFileName = "mgd.datasources.xml"; //$NON-NLS-1$
769
                String config = CDMServerUtils.convertEditorToServerConfig();
770
                File managedServerConfigFile;
771
                int maxUnits = 50;
772
                monitor.beginTask(Messages.RemotingLoginDialog_TASK_LAUNCHING_SERVER, maxUnits);
773
                try {
774
                    monitor.subTask(String.format(Messages.RemotingLoginDialog_GENERATING_CONFIG_FILE, selectedCdmInstance.getName()));
775
                    managedServerConfigFile = CDMServerUtils.writeManagedServerConfig(config, mgdServerConfigFileName);
776
                    monitor.worked(1);
777
                    CdmStore.setManagedServer(new CDMServer(selectedCdmInstance.getName(), managedServerConfigFile));
778
                    monitor.subTask(Messages.RemotingLoginDialog_STARTING_MGD_SERVER);
779
                    CdmStore.getManagedServer().start(false, RemotingLoginDialog.this);
780
                    int serverUnits = 0;
781

    
782
                    // the following loop is a 'fake' progress monitoring where the progress
783
                    // bar is advanced by one unit every second until maxUnits -2
784
                    while(!CdmStore.getManagedServer().isStarted() && !CdmStore.getManagedServer().isFailed()) {
785
                        if(serverUnits < maxUnits - 2) {
786
                            try {
787
                                Thread.sleep(1000);
788
                            } catch (InterruptedException e) {
789
                            }
790
                            monitor.worked(1);
791
                            serverUnits++;
792
                        }
793
                    }
794
                    Display.getDefault().asyncExec(new Runnable() {
795
                        @Override
796
                        public void run() {
797
                                hide(false);
798
                                updateManagedServerControls();
799
                                connect();
800
                            }
801
                    });
802
                } catch (IOException ioe) {
803
                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_GENERATING_CONFIG_FILE,
804
                            this,
805
                            ioe.getMessage(),
806
                            TaxeditorStorePlugin.PLUGIN_ID,
807
                            ioe,
808
                            true);
809
                } catch (CDMEmbeddedServerException cse) {
810
                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STARTING_SERVER,
811
                            this,
812
                            cse.getMessage(),
813
                            TaxeditorStorePlugin.PLUGIN_ID,
814
                            cse,
815
                            true);
816
                } finally {
817
                    monitor.done();
818
                }
819
                return Status.OK_STATUS;
820
            }
821
        };
822

    
823
        // configure the job
824
        job.setProperty(IProgressConstants.KEEP_PROPERTY, true);
825
        job.setUser(true);
826
        // schedule job
827
        hide(true);
828
        job.schedule();
829
    }
830

    
831
    private void stopManagedServer() {
832
        try {
833
            CdmStore.getManagedServer().stop();
834
        } catch (Exception e) {
835
            MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STOPPING_SERVER,
836
                    this,
837
                    String.format(Messages.RemotingLoginDialog_COULD_NOT_STOP_SERVER, CdmStore.getManagedServer().getPort()),
838
                    TaxeditorStorePlugin.PLUGIN_ID,
839
                    e,
840
                    true);
841
        }
842
        CdmStore.setManagedServer(null);
843
        updateManagedServerControls();
844
    }
845

    
846
    private int getManagedServerPort() {
847
        return CdmStore.getManagedServer() == null ? CdmServerInfo.NULL_PORT : CdmStore.getManagedServer().getPort();
848
    }
849

    
850
    private void checkSelectedCdmInstance() {
851
        boolean available = false;
852
        String status = STATUS_NOT_AVAILABLE;
853
        String message = null;
854

    
855
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE)) {
856
            try {
857
                if(selectedCsii.pingInstance(selectedCdmInstance, getPort())) {
858
                    status = STATUS_AVAILABLE;
859
                    available = true;
860
                } else {
861
                    status = STATUS_NOT_AVAILABLE;
862
                    available = false;
863
                }
864

    
865
                if(available) {
866
                    txtServerCDMVersion.setText(selectedCsii.getCdmRemoteSource(selectedCdmInstance, getPort()).getDbSchemaVersion());
867
                    int compareDbSchemaVersion = selectedCsii.compareDbSchemaVersion(selectedCdmInstance, getPort());
868
                    int compareCdmlibServicesVersion = 0;
869
                    boolean disableServicesApiTimestampCheck =
870
                            PreferencesUtil.getBooleanValue((IPreferenceKeys.DISABLE_SERVICES_API_TIMESTAMP_CHECK));
871
                    if(!disableServicesApiTimestampCheck) {
872
                        compareCdmlibServicesVersion = selectedCsii.compareCdmlibServicesVersion();
873
                    }
874
                    if(compareDbSchemaVersion > 0 || compareCdmlibServicesVersion > 0) {
875
                        status =  STATUS_NOT_COMPATIBLE;
876
                        available = false;
877
                        message = MESG_COMPATIBLE_EDITOR_OLD;
878
                    } else if(compareDbSchemaVersion < 0 || compareCdmlibServicesVersion < 0) {
879
                        status = STATUS_NOT_COMPATIBLE;
880
                        available = false;
881
                        message = MESG_COMPATIBLE_SERVER_OLD;
882
                    } else {
883
                        status =  STATUS_AVAILABLE;
884
                        available = true;
885
                        message = ""; //$NON-NLS-1$
886
                    }
887
                }
888
            } catch (Exception e) {
889
                txtCdmInstanceStatus.setToolTipText(e.getMessage());
890
            } finally {
891
                btnConnect.setEnabled(available);
892
                txtCdmInstanceStatus.setText(status);
893
                if(!StringUtils.isBlank(message)) {
894
                    setMessage(message);
895
                }
896
            }
897
        }
898
    }
899

    
900
    private void connect() {
901
        checkSelectedCdmInstance();
902

    
903
        if(!txtCdmInstanceStatus.getText().equals(STATUS_AVAILABLE)) {
904
            return;
905
        }
906

    
907
        ICdmRemoteSource source = selectedCsii.getCdmRemoteSource(selectedCdmInstance, getPort());
908

    
909
        if(!validateLogin(source)) {
910
            return;
911
        }
912

    
913
        try {
914
            CdmStore.connect(source, this);
915
        } catch (Exception e) {
916
            // Do not expect anything to go wrong at this point, so we throw a runtime exception
917
            // if any problems
918
            throw new RuntimeException(e);
919
        }
920

    
921
    }
922

    
923

    
924
    public boolean isRememberMe() {
925
        return btnRememberMe.getSelection();
926
    }
927

    
928
    private void persistPrefLastServerInstance() {
929
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
930
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
931

    
932
        lastServerInstancePrefs.put(LAST_SERVER_KEY, selectedCsii.getName());
933
        lastServerInstancePrefs.put(LAST_INSTANCE_KEY, selectedCdmInstance.getName());
934

    
935
        flushPreferences(lastServerInstancePrefs);
936
    }
937

    
938
    private void persistPrefCredentials() {
939
         IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
940
         Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
941
         credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
942
         credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
943
         flushPreferences(credentialsPrefs);
944
    }
945

    
946
    private void removePrefCredentials() {
947
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
948
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
949
        credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
950
        credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
951
        removePreferences(credentialsPrefs);
952
   }
953
    private void removePreferences(Preferences prefs) {
954
        try {
955
            prefs.removeNode();
956
        } catch (BackingStoreException bse) {
957
            setMessage(bse.getMessage());
958
        }
959
    }
960
    private void flushPreferences(Preferences prefs) {
961
        try {
962
            prefs.flush();
963
        } catch (BackingStoreException bse) {
964
            setMessage(bse.getMessage());
965
        }
966
    }
967

    
968

    
969

    
970
    private void readPrefCredentials() {
971
        String username, password;
972
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
973
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
974
        username = credentialsPrefs.get(getUsernamePrefKey(), ""); //$NON-NLS-1$
975
        txtLogin.setText(username);
976
        password = credentialsPrefs.get(getPasswordPrefKey(),""); //$NON-NLS-1$
977
        txtPassword.setText(password);
978
        if(username.isEmpty() || password.isEmpty()) {
979
            autoConnect = false;
980
        }
981
    }
982

    
983
    private void readPrefLastServerInstance() {
984
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
985
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
986

    
987
        serverName = lastServerInstancePrefs.get(LAST_SERVER_KEY, null);
988
        instanceName = lastServerInstancePrefs.get(LAST_INSTANCE_KEY, null);
989
    }
990

    
991
    private void emptyCredentials() {
992
        txtLogin.setText(""); //$NON-NLS-1$
993
        txtPassword.setText(""); //$NON-NLS-1$
994
    }
995

    
996
    private String getUsernamePrefKey() {
997
        return selectedCsii.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + USERNAME_SUFFIX;
998
    }
999

    
1000
    private String getPasswordPrefKey() {
1001
        return selectedCsii.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + PASSWORD_SUFFIX;
1002
    }
1003

    
1004
    private boolean validateLogin(ICdmRemoteSource remoteSource) {
1005
        if(getUsername() == null || getUsername().isEmpty()) {
1006
            setMessage(Messages.RemotingLoginDialog_LOGIN_CANNOT_BE_EMPTY);
1007
            return false;
1008
        }
1009
        if(getPassword() == null || getPassword().isEmpty()) {
1010
            setMessage(Messages.RemotingLoginDialog_PASSWORD_CANNOT_BE_EMPTY);
1011
            return false;
1012
        }
1013

    
1014

    
1015
        try {
1016
            IUserService userService = CdmApplicationRemoteConfiguration.getUserService(remoteSource);
1017
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(getUsername(), getPassword());
1018
            CdmApplicationRemoteConfiguration.getAuthenticationManager(userService).authenticate(token);
1019
        } catch(BadCredentialsException e){
1020
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1021
            return false;
1022
        } catch(LockedException e){
1023
            setMessage(LoginManager.ACCOUNT_LOCKED_MESSAGE);
1024
            return false;
1025
        } catch(IllegalArgumentException e){
1026
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1027
            return false;
1028
        }
1029
        return true;
1030
    }
1031

    
1032
    public String getUsername() {
1033
        return txtLogin.getText();
1034
    }
1035

    
1036
    public String getPassword() {
1037
        return txtPassword.getText();
1038
    }
1039

    
1040
    public void setMessage(String message) {
1041
        if(message != null && !message.isEmpty()) {
1042
//            if(message.length() > 50) {
1043
//                styledTxtMessage.setToolTipText(message);
1044
//                message = message.substring(0,50) + "..."; //$NON-NLS-1$
1045
//            }
1046
            styledTxtMessage.setText(message);
1047
            styledTxtMessage.setVisible(true);
1048
            ((GridData)styledTxtMessage.getLayoutData()).exclude = false;
1049
            shlConnect.setSize(MIN_WIDTH, getHeightWithoutMessage() + MESSAGE_HEIGHT);
1050
            shlConnect.setMinimumSize(MIN_WIDTH, getHeightWithoutMessage() + MESSAGE_HEIGHT);
1051
        } else {
1052
            if (!styledTxtMessage.isDisposed()){
1053
                styledTxtMessage.setText(""); //$NON-NLS-1$
1054
                styledTxtMessage.setVisible(false);
1055
                ((GridData)styledTxtMessage.getLayoutData()).exclude = true;
1056
            }
1057
            if(!shlConnect.isDisposed()){
1058
                shlConnect.setSize(MIN_WIDTH, getHeightWithoutMessage());
1059
                shlConnect.setMinimumSize(MIN_WIDTH, getHeightWithoutMessage());
1060
            }
1061
        }
1062
        if (!remotingComposite.isDisposed()){
1063
            remotingComposite.layout();
1064
        }
1065
    }
1066

    
1067
    private int getHeightWithoutMessage() {
1068
        if(xpndblcmpstAdvanced.isExpanded()) {
1069
            return MIN_EXP_HEIGHT;
1070
        } else {
1071
            return MIN_HEIGHT;
1072
        }
1073
    }
1074

    
1075

    
1076
    public void hide(boolean isHidden) {
1077
        if (!shlConnect.isDisposed()){
1078
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1079
                shlConnect.setVisible(!isHidden);
1080
            }
1081
        }
1082
    }
1083
    public void dispose() {
1084
        if (!shlConnect.isDisposed()){
1085
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1086
                shlConnect.dispose();
1087
            }
1088
        }
1089
    }
1090

    
1091
    public void onComplete() {
1092
        Display.getDefault().asyncExec(new Runnable() {
1093
            @Override
1094
            public void run() {
1095
                if(selectedCdmInstance!=null){
1096
                    if(isRememberMe()) {
1097
                        persistPrefCredentials();
1098
                    }else{
1099
                        removePrefCredentials();
1100
                    }
1101
                    persistPrefLastServerInstance();
1102
                }
1103
                dispose();
1104
            }
1105
        });
1106
    }
1107

    
1108
    private String generateLastModifiedTooltip(String cdmlibLastModified) {
1109
        if(StringUtils.isBlank(cdmlibLastModified)) {
1110
            return ""; //$NON-NLS-1$
1111
        }
1112
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.z"); //$NON-NLS-1$
1113
        Date cdmlibLastModifiedDate;
1114
        String cdmlibLastModifiedTimestamp = ""; //$NON-NLS-1$
1115

    
1116
        cdmlibLastModifiedDate = new Date(Long.valueOf(cdmlibLastModified));
1117
        cdmlibLastModifiedTimestamp = sdf.format(cdmlibLastModifiedDate);
1118

    
1119
        return cdmlibLastModifiedTimestamp;
1120
    }
1121

    
1122
    private void setEditorInfo() {
1123
        txtEditorCDMVersion.setText(CdmMetaData.getDbSchemaVersion());
1124
        String editorVersionTimestamp = generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified());
1125
        txtEditorVersion.setText(CdmApplicationState.getCdmlibVersion() + ":" + editorVersionTimestamp); //$NON-NLS-1$
1126
    }
1127

    
1128
    private void clearOnServerChange() {
1129
        setMessage(""); //$NON-NLS-1$
1130
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1131
        txtServerVersion.setText(""); //$NON-NLS-1$
1132
        txtServerVersion.setToolTipText(""); //$NON-NLS-1$
1133
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1134
        comboCdmInstance.removeAll();
1135
        txtCdmInstanceStatus.setText(""); //$NON-NLS-1$
1136
        txtPort.setEditable(false);
1137
        txtPort.setEnabled(false);
1138
    }
1139

    
1140
    private void clearOnInstanceChange() {
1141
        setMessage(""); //$NON-NLS-1$
1142
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1143
    }
1144

    
1145
    /**
1146
     * {@inheritDoc}
1147
     */
1148
    @Override
1149
    public void handleError(final Throwable t) {
1150

    
1151
        Display.getDefault().syncExec(new Runnable() {
1152
            @Override
1153
            public void run() {
1154
                serverJob.cancel();
1155

    
1156
                String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
1157
                String  message = t.getMessage();
1158

    
1159

    
1160
                MessagingUtils.errorDialog(title,
1161
                        this,
1162
                        message,
1163
                        TaxeditorStorePlugin.PLUGIN_ID,
1164
                        t,
1165
                        true);
1166
            }
1167
        });
1168
    }
1169

    
1170

    
1171
}
(5-5/7)