Project

General

Profile

Download (48.3 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
        txtCdmServerStatus.setLayoutData(gd_txtCdmServerStatus);
266

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

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

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

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

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

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

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

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

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

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

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

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

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

    
380
        styledTxtMessage = new StyledText(remotingComposite, SWT.NONE);
381
        styledTxtMessage.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
382
        styledTxtMessage.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
383
        styledTxtMessage.setFont(SWTResourceManager.getFont(UBUNTU, 12, SWT.BOLD));
384
        styledTxtMessage.setSelectionBackground(SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION_TEXT));
385
        styledTxtMessage.setSelectionForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
386
        styledTxtMessage.setDoubleClickEnabled(false);
387
        styledTxtMessage.setEditable(false);
388
        styledTxtMessage.setWordWrap(true);
389
        GridData gd_styledTxtMessage = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
390
        gd_styledTxtMessage.exclude = true;
391
        gd_styledTxtMessage.minimumHeight = MESSAGE_HEIGHT;
392
        gd_styledTxtMessage.heightHint = MESSAGE_HEIGHT;
393
        styledTxtMessage.setLayoutData(gd_styledTxtMessage);
394

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

    
408
            }
409
            @Override
410
            public void expansionStateChanging(ExpansionEvent e) {
411
            }
412
        });
413
        xpndblcmpstAdvanced.setText(Messages.RemotingLoginDialog_LABEL_ADVANCED);
414
        xpndblcmpstAdvanced.setExpanded(true);
415

    
416
        compAdvanced = new Composite(xpndblcmpstAdvanced, SWT.NONE);
417
        xpndblcmpstAdvanced.setClient(compAdvanced);
418
        compAdvanced.setLayout(new GridLayout(4, false));
419

    
420
        lblPort = new Label(compAdvanced, SWT.CENTER);
421
        lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
422
        lblPort.setSize(0, 0);
423
        lblPort.setText(Messages.RemotingLoginDialog_LABEL_PORT);
424
        lblPort.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
425

    
426
        txtPort = new Text(compAdvanced, SWT.BORDER);
427
        GridData gd_txtPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
428
        gd_txtPort.minimumWidth = 50;
429
        gd_txtPort.widthHint = 50;
430
        txtPort.setLayoutData(gd_txtPort);
431

    
432
        lblServerVersion = new Label(compAdvanced, SWT.CENTER);
433
        lblServerVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
434
        lblServerVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDMLIB_VERSION);
435
        lblServerVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
436

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

    
450
        lblEditorVersion = new Label(compAdvanced, SWT.CENTER);
451
        lblEditorVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
452
        lblEditorVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDMLIB_VERSION);
453
        lblEditorVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
454

    
455
        txtEditorVersion = new Text(compAdvanced, SWT.BORDER);
456
        txtEditorVersion.setEditable(false);
457
        txtEditorVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
458
        new Label(compAdvanced, SWT.NONE);
459
        new Label(compAdvanced, SWT.NONE);
460

    
461
        lblServerCDMVersion = new Label(compAdvanced, SWT.CENTER);
462
        lblServerCDMVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
463
        lblServerCDMVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDM_VERSION);
464
        lblServerCDMVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
465

    
466
        txtServerCDMVersion = new Text(compAdvanced, SWT.BORDER);
467
        txtServerCDMVersion.setEditable(false);
468
        txtServerCDMVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
469
        new Label(compAdvanced, SWT.NONE);
470
        new Label(compAdvanced, SWT.NONE);
471

    
472
        lblEditorCDMVersion = new Label(compAdvanced, SWT.CENTER);
473
        lblEditorCDMVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
474
        lblEditorCDMVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDM_VERSION);
475
        lblEditorCDMVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
476

    
477
        txtEditorCDMVersion = new Text(compAdvanced, SWT.BORDER);
478
        txtEditorCDMVersion.setEditable(false);
479
        txtEditorCDMVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
480

    
481
    }
482

    
483
	private void connectButtonPressed() {
484
		if(selectedCsii.isLocalhostMgd() && !isSelectedCdmInstanceRunningInManagedServer()) {
485
			startManagedServer();
486
		} else {
487
			connect();
488
			if (CdmStore.isActive() && CdmStore.currentAuthentiationHasOneOfRoles(Role.ROLE_REMOTING)){
489
			    PreferencesUtil.setNomenclaturalCodePreferences();
490
			}
491

    
492
		}
493
	}
494

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

    
537

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

    
557
    private void updateSelectedCdmServer() {
558
        int selIndex = comboCdmServer.getSelectionIndex();
559
        if(selIndex != -1) {
560
            selectedCsii = csiiMap.get(comboCdmServer.getItem(selIndex));
561
        }
562
    }
563

    
564
    private void updatePort() {
565
        txtPort.setText(""); //$NON-NLS-1$
566
        if(selectedCsii != null) {
567
            int port = selectedCsii.getPort();
568
            if(port == CdmServerInfo.NULL_PORT) {
569
                txtPort.setText(CdmServerInfo.NULL_PORT_STRING);
570
            } else {
571
                txtPort.setText(String.valueOf(port));
572
            }
573
        }
574
    }
575

    
576
    private int getPort() {
577
        int port = CdmServerInfo.NULL_PORT;
578
        try {
579
            port = Integer.valueOf(txtPort.getText());
580
        } catch (NumberFormatException nfe) {
581
            if(!CdmServerInfo.NULL_PORT_STRING.equals(txtPort.getText())) {
582
                setMessage(Messages.RemotingLoginDialog_MESSAGE_PORT_SHOULD_BE_INTEGER);
583
            }
584
        }
585
        return port;
586
    }
587

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

    
621

    
622
    private void populateCdmInstanceCombo(final boolean forceRefresh) {
623
        comboCdmInstance.removeAll();
624
        comboCdmInstance.setEnabled(false);
625
        btnConnect.setEnabled(false);
626
        txtCdmInstanceStatus.setText(STATUS_RETRIEVING);
627
        txtCdmInstanceStatus.setToolTipText(""); //$NON-NLS-1$
628

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

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

    
681
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE) && !isDevRemoteSource) {
682
            // Start the Job
683
            serverJob.schedule();
684
        }
685
    }
686

    
687
    private void disableCdmInstanceControls(String cdmInstanceStatus, String tooltip) {
688
        txtCdmInstanceStatus.setText(cdmInstanceStatus);
689
        txtCdmInstanceStatus.setToolTipText(tooltip);
690
        comboCdmInstance.setEnabled(false);
691
        btnConnect.setEnabled(false);
692

    
693
    }
694
    private void refreshCdmInstance() {
695
        txtCdmInstanceStatus.setText(STATUS_CHECKING_AVAILABILITY);
696
        clearOnInstanceChange();
697
        updateSelectedCdmInstance();
698
        checkSelectedCdmInstance();
699
        updateManagedServerControls();
700
    }
701

    
702
    private void updateSelectedCdmInstance() {
703
        int selIndex = comboCdmInstance.getSelectionIndex();
704
        if(selIndex != -1) {
705
            selectedCdmInstance = selectedCsii.getInstanceFromName(comboCdmInstance.getItem(selIndex));
706

    
707
            if(loadLoginPrefs && !isDevRemoteSource) {
708
                readPrefCredentials();
709
            }
710
        }
711
    }
712

    
713
    private void updateManagedServerControls() {
714
        if(selectedCsii.isLocalhostMgd()) {
715
            if(isSelectedCdmInstanceRunningInManagedServer()) {
716
                txtCdmInstanceStatus.setText(STATUS_STARTED);
717
            } else {
718
                txtCdmInstanceStatus.setText(STATUS_NOT_STARTED);
719
            }
720
            btnConnect.setEnabled(true);
721
            selectedCsii.setPort(getManagedServerPort());
722
            updatePort();
723
        }
724

    
725

    
726
        if(isManagedServerRunning()) {
727
            btnStopServer.setEnabled(true);
728
        } else {
729
            btnStopServer.setEnabled(false);
730
        }
731
    }
732

    
733
    private boolean isManagedServerRunning() {
734
        return CdmStore.getManagedServer() != null && CdmStore.getManagedServer().isAlive();
735
    }
736

    
737
    private boolean isSelectedCdmInstanceRunningInManagedServer() {
738
        return CdmStore.getManagedServer() != null &&
739
                CdmStore.getManagedServer().isAlive() &&
740
                selectedCsii.isLocalhostMgd() &&
741
                CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName());
742
    }
743

    
744
    private void startManagedServer() {
745
        if(isManagedServerRunning()) {
746
            if(CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())) {
747
                return;
748
            } else {
749
                Display.getDefault().syncExec(new Runnable() {
750
                    @Override
751
                    public void run() {
752
                        stopManagedServer();
753
                    }
754
                });
755
            }
756
        }
757

    
758

    
759
        Job job = new Job(Messages.RemotingLoginDialog_JOB_SERVER_LAUNCH) {
760

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

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

    
818
        // configure the job
819
        job.setProperty(IProgressConstants.KEEP_PROPERTY, true);
820
        job.setUser(true);
821
        // schedule job
822
        hide(true);
823
        job.schedule();
824
    }
825

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

    
841
    private int getManagedServerPort() {
842
        return CdmStore.getManagedServer() == null ? CdmServerInfo.NULL_PORT : CdmStore.getManagedServer().getPort();
843
    }
844

    
845
    private void checkSelectedCdmInstance() {
846
        boolean available = false;
847
        String status = STATUS_NOT_AVAILABLE;
848
        String message = null;
849

    
850
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE)) {
851
            try {
852
                if(selectedCsii.pingInstance(selectedCdmInstance, getPort())) {
853
                    status = STATUS_AVAILABLE;
854
                    available = true;
855
                } else {
856
                    status = STATUS_NOT_AVAILABLE;
857
                    available = false;
858
                }
859

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

    
895
    private void connect() {
896
        checkSelectedCdmInstance();
897

    
898
        if(!txtCdmInstanceStatus.getText().equals(STATUS_AVAILABLE)) {
899
            return;
900
        }
901

    
902
        ICdmRemoteSource source = selectedCsii.getCdmRemoteSource(selectedCdmInstance, getPort());
903

    
904
        if(!validateLogin(source)) {
905
            return;
906
        }
907

    
908
        try {
909
            CdmStore.connect(source, this);
910
        } catch (Exception e) {
911
            // Do not expect anything to go wrong at this point, so we throw a runtime exception
912
            // if any problems
913
            throw new RuntimeException(e);
914
        }
915

    
916
    }
917

    
918

    
919
    public boolean isRememberMe() {
920
        return btnRememberMe.getSelection();
921
    }
922

    
923
    private void persistPrefLastServerInstance() {
924
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
925
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
926

    
927
        lastServerInstancePrefs.put(LAST_SERVER_KEY, selectedCsii.getName());
928
        lastServerInstancePrefs.put(LAST_INSTANCE_KEY, selectedCdmInstance.getName());
929

    
930
        flushPreferences(lastServerInstancePrefs);
931
    }
932

    
933
    private void persistPrefCredentials() {
934
         IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
935
         Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
936
         credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
937
         credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
938
         flushPreferences(credentialsPrefs);
939
    }
940

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

    
963

    
964

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

    
978
    private void readPrefLastServerInstance() {
979
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
980
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
981

    
982
        serverName = lastServerInstancePrefs.get(LAST_SERVER_KEY, null);
983
        instanceName = lastServerInstancePrefs.get(LAST_INSTANCE_KEY, null);
984
    }
985

    
986
    private void emptyCredentials() {
987
        txtLogin.setText(""); //$NON-NLS-1$
988
        txtPassword.setText(""); //$NON-NLS-1$
989
    }
990

    
991
    private String getUsernamePrefKey() {
992
        return selectedCsii.toString(selectedCdmInstance.getName(), getPort()) + USERNAME_SUFFIX;
993
    }
994

    
995
    private String getPasswordPrefKey() {
996
        return selectedCsii.toString(selectedCdmInstance.getName(), getPort()) + PASSWORD_SUFFIX;
997
    }
998

    
999
    private boolean validateLogin(ICdmRemoteSource remoteSource) {
1000
        if(getUsername() == null || getUsername().isEmpty()) {
1001
            setMessage(Messages.RemotingLoginDialog_LOGIN_CANNOT_BE_EMPTY);
1002
            return false;
1003
        }
1004
        if(getPassword() == null || getPassword().isEmpty()) {
1005
            setMessage(Messages.RemotingLoginDialog_PASSWORD_CANNOT_BE_EMPTY);
1006
            return false;
1007
        }
1008

    
1009

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

    
1027
    public String getUsername() {
1028
        return txtLogin.getText();
1029
    }
1030

    
1031
    public String getPassword() {
1032
        return txtPassword.getText();
1033
    }
1034

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

    
1062
    private int getHeightWithoutMessage() {
1063
        if(xpndblcmpstAdvanced.isExpanded()) {
1064
            return MIN_EXP_HEIGHT;
1065
        } else {
1066
            return MIN_HEIGHT;
1067
        }
1068
    }
1069

    
1070

    
1071
    public void hide(boolean isHidden) {
1072
        if (!shlConnect.isDisposed()){
1073
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1074
                shlConnect.setVisible(!isHidden);
1075
            }
1076
        }
1077
    }
1078
    public void dispose() {
1079
        if (!shlConnect.isDisposed()){
1080
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1081
                shlConnect.dispose();
1082
            }
1083
        }
1084
    }
1085

    
1086
    public void onComplete() {
1087
        Display.getDefault().asyncExec(new Runnable() {
1088
            @Override
1089
            public void run() {
1090
                if(!isDevRemoteSource) {
1091
                    if(isRememberMe()) {
1092
                        persistPrefCredentials();
1093
                    }else{
1094
                    	removePrefCredentials();
1095
                    }
1096
                    persistPrefLastServerInstance();
1097
                }
1098
                dispose();
1099
            }
1100
        });
1101
    }
1102

    
1103
    private String generateLastModifiedTooltip(String cdmlibLastModified) {
1104
        if(StringUtils.isBlank(cdmlibLastModified)) {
1105
            return ""; //$NON-NLS-1$
1106
        }
1107
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.z"); //$NON-NLS-1$
1108
        Date cdmlibLastModifiedDate;
1109
        String cdmlibLastModifiedTimestamp = ""; //$NON-NLS-1$
1110

    
1111
        cdmlibLastModifiedDate = new Date(Long.valueOf(cdmlibLastModified));
1112
        cdmlibLastModifiedTimestamp = sdf.format(cdmlibLastModifiedDate);
1113

    
1114
        return cdmlibLastModifiedTimestamp;
1115
    }
1116

    
1117
    private void setEditorInfo() {
1118
        txtEditorCDMVersion.setText(CdmMetaData.getDbSchemaVersion());
1119
        String editorVersionTimestamp = generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified());
1120
        txtEditorVersion.setText(CdmApplicationState.getCdmlibVersion() + ":" + editorVersionTimestamp); //$NON-NLS-1$
1121
    }
1122

    
1123
    private void clearOnServerChange() {
1124
        setMessage(""); //$NON-NLS-1$
1125
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1126
        txtServerVersion.setText(""); //$NON-NLS-1$
1127
        txtServerVersion.setToolTipText(""); //$NON-NLS-1$
1128
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1129
        comboCdmInstance.removeAll();
1130
        txtCdmInstanceStatus.setText(""); //$NON-NLS-1$
1131
        txtPort.setEditable(false);
1132
        txtPort.setEnabled(false);
1133
    }
1134

    
1135
    private void clearOnInstanceChange() {
1136
        setMessage(""); //$NON-NLS-1$
1137
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1138
    }
1139

    
1140
    /**
1141
     * {@inheritDoc}
1142
     */
1143
    @Override
1144
    public void handleError(final Throwable t) {
1145

    
1146
        Display.getDefault().syncExec(new Runnable() {
1147
            @Override
1148
            public void run() {
1149
                serverJob.cancel();
1150

    
1151
                String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
1152
                String  message = t.getMessage();
1153

    
1154

    
1155
                MessagingUtils.errorDialog(title,
1156
                        this,
1157
                        message,
1158
                        TaxeditorStorePlugin.PLUGIN_ID,
1159
                        t,
1160
                        true);
1161
            }
1162
        });
1163
    }
1164

    
1165

    
1166
}
(5-5/7)