Project

General

Profile

Download (48.9 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.net.SocketTimeoutException;
14
import java.text.SimpleDateFormat;
15
import java.util.Date;
16
import java.util.HashMap;
17
import java.util.List;
18
import java.util.Map;
19

    
20
import org.apache.commons.lang.StringUtils;
21
import org.apache.log4j.Logger;
22
import org.eclipse.core.runtime.IProgressMonitor;
23
import org.eclipse.core.runtime.IStatus;
24
import org.eclipse.core.runtime.Status;
25
import org.eclipse.core.runtime.jobs.Job;
26
import org.eclipse.core.runtime.preferences.ConfigurationScope;
27
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
28
import org.eclipse.jface.layout.GridDataFactory;
29
import org.eclipse.swt.SWT;
30
import org.eclipse.swt.SWTException;
31
import org.eclipse.swt.custom.StyledText;
32
import org.eclipse.swt.events.KeyAdapter;
33
import org.eclipse.swt.events.KeyEvent;
34
import org.eclipse.swt.events.MouseAdapter;
35
import org.eclipse.swt.events.MouseEvent;
36
import org.eclipse.swt.events.SelectionAdapter;
37
import org.eclipse.swt.events.SelectionEvent;
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.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
 * @author cmathew
84
 * @date 20 Jan 2015
85
 */
86
public class RemotingLoginDialog extends Dialog implements ICDMServerError {
87

    
88
    private Logger logger = Logger.getLogger(getClass());
89

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

    
101
    private final Map<String, CdmServerInfo> csiiMap = new HashMap<>();
102

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

    
112
    private final static String MESG_COMPATIBLE_EDITOR_OLD = Messages.RemotingLoginDialog_UPDATE_EDITOR;
113
    private final static String MESG_COMPATIBLE_SERVER_OLD = Messages.RemotingLoginDialog_CHOOSE_COMPATIBLE_CDM_SERVER;
114

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

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

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

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

    
145
//    private final int MIN_WIDTH = 530;
146
//    private final int MIN_HEIGHT = 220;
147
//    private final int MIN_EXP_HEIGHT = 380;
148

    
149
    private final int MESSAGE_HEIGHT = 50;
150
    private Label lblEditorVersion;
151
    private Text txtEditorVersion;
152
    private Label lblServerCDMVersion;
153
    private Text txtServerCDMVersion;
154
    private Label lblEditorCDMVersion;
155
    private Text txtEditorCDMVersion;
156

    
157
    private String serverName, instanceName;
158
    private boolean autoConnect = false;
159
    private boolean loadLoginPrefs = true;
160
    private boolean isDevRemoteSource = false;
161
    private Job serverJob;
162

    
163
    /**
164
     * Create the dialog.
165
     * @param parent
166
     * @param style
167
     */
168
    public RemotingLoginDialog(Shell parent, int style) {
169
        super(parent, style);
170
        setText(Messages.RemotingLoginDialog_LABEL_LOGIN);
171
    }
172

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

    
181

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

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

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

    
201
        setEditorInfo();
202
        populateCdmServerCombo();
203
        shlConnect.pack(true);
204
        shlConnect.open();
205

    
206
        xpndblcmpstAdvanced.setExpanded(false);
207

    
208
        Display display = getParent().getDisplay();
209

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

    
218
        return result;
219
    }
220

    
221
    /**
222
     * Create contents of the dialog.
223
     */
224
    private void createContents() {
225
        shlConnect = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE);
226
        shlConnect.setText(Messages.RemotingLoginDialog_LABEL_CONNECT);
227
        shlConnect.setLayout(new FillLayout(SWT.HORIZONTAL));
228

    
229
        remotingComposite = new Composite(shlConnect, SWT.NONE);
230
        remotingComposite.setLayout(new GridLayout(1, false));
231

    
232
        Composite cdmServerComposite = new Composite(remotingComposite, SWT.NONE);
233
        GridData gd_cdmServerComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
234
        cdmServerComposite.setLayoutData(gd_cdmServerComposite);
235
        cdmServerComposite.setLayout(new GridLayout(4, false));
236

    
237
        Label lblCdmServer = new Label(cdmServerComposite, SWT.NONE);
238
        lblCdmServer.setText(Messages.RemotingLoginDialog_LABEL_CDM_SERVER);
239
        lblCdmServer.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
240
        lblCdmServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
241

    
242
        comboCdmServer = new Combo(cdmServerComposite, SWT.READ_ONLY);
243
        comboCdmServer.addSelectionListener(new SelectionAdapter() {
244
            @Override
245
            public void widgetSelected(SelectionEvent e) {
246
                refreshCdmServer();
247
            }
248
        });
249
        GridData gd_comboCdmServer = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
250
        comboCdmServer.setLayoutData(gd_comboCdmServer);
251
        comboCdmServer.select(0);
252

    
253
        txtCdmServerStatus = new Text(cdmServerComposite, SWT.BORDER);
254
        txtCdmServerStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
255
        txtCdmServerStatus.setEditable(false);
256
        GridData gd_txtCdmServerStatus = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
257

    
258
        txtCdmServerStatus.setLayoutData(gd_txtCdmServerStatus);
259

    
260
        btnCdmServerRefresh = new Button(cdmServerComposite, SWT.NONE);
261
        btnCdmServerRefresh.addSelectionListener(new SelectionAdapter() {
262
            @Override
263
            public void widgetSelected(SelectionEvent e) {
264
                refreshCdmServer();
265
            }
266
        });
267
        btnCdmServerRefresh.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
268
        btnCdmServerRefresh.setText(Messages.RemotingLoginDialog_LABEL_REFRESH);
269

    
270
        Label lblCdmInstance = new Label(cdmServerComposite, SWT.NONE);
271
        GridData gd_lblCdmInstance = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
272
        //gd_lblCdmInstance.heightHint = 30;
273
        lblCdmInstance.setLayoutData(gd_lblCdmInstance);
274
        lblCdmInstance.setText(Messages.RemotingLoginDialog_LABEL_CDM_INSTANCE);
275
        lblCdmInstance.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
276

    
277
        comboCdmInstance = new Combo(cdmServerComposite, SWT.READ_ONLY);
278
        comboCdmInstance.addSelectionListener(new SelectionAdapter() {
279
            @Override
280
            public void widgetSelected(SelectionEvent e) {
281
                refreshCdmInstance();
282
            }
283
        });
284
        GridData gd_comboCdmInstance = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
285
        comboCdmInstance.setLayoutData(gd_comboCdmInstance);
286
        comboCdmInstance.select(0);
287

    
288
        txtCdmInstanceStatus = new Text(cdmServerComposite, SWT.BORDER);
289
        txtCdmInstanceStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
290
        txtCdmInstanceStatus.setEditable(false);
291
        GridData gd_txtCdmInstanceStatus = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
292
        txtCdmInstanceStatus.setLayoutData(gd_txtCdmInstanceStatus);
293

    
294
        btnCdmInstanceRefresh = new Button(cdmServerComposite, SWT.FLAT);
295
        btnCdmInstanceRefresh.addSelectionListener(new SelectionAdapter() {
296
            @Override
297
            public void widgetSelected(SelectionEvent e) {
298
                refreshCdmInstance();
299
            }
300
        });
301
        GridData gd_btnCdmInstanceRefresh = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
302
        btnCdmInstanceRefresh.setLayoutData(gd_btnCdmInstanceRefresh);
303
        btnCdmInstanceRefresh.setText(Messages.RemotingLoginDialog_LABEL_REFRESH);
304

    
305
        loginComposite = new Composite(remotingComposite, SWT.NONE);
306
        GridData gd_loginComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
307
        loginComposite.setLayoutData(gd_loginComposite);
308
        GridLayout gl_loginComposite = new GridLayout(6, false);
309
        gl_loginComposite.marginTop = 5;
310
        loginComposite.setLayout(gl_loginComposite);
311

    
312
        lblLogin = new Label(loginComposite, SWT.CENTER);
313
        GridData gd_lblLogin = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
314
        lblLogin.setLayoutData(gd_lblLogin);
315
        lblLogin.setText(Messages.RemotingLoginDialog_LABEL_LOGIN_COLON);
316
        lblLogin.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
317

    
318
        txtLogin = new Text(loginComposite, SWT.BORDER);
319
        GridData gd_txtLogin = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
320
        gd_txtLogin.minimumWidth = 80;
321
        txtLogin.setLayoutData(gd_txtLogin);
322

    
323
        lblPassword = new Label(loginComposite, SWT.CENTER);
324
        lblPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
325
        lblPassword.setText(Messages.RemotingLoginDialog_LABEL_PASSWORD);
326
        lblPassword.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
327

    
328
        txtPassword = new Text(loginComposite, SWT.BORDER | SWT.PASSWORD);
329
        GridData gd_txtPassword = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
330
        gd_txtPassword.minimumWidth = 80;
331
        txtPassword.setLayoutData(gd_txtPassword);
332
        new Label(loginComposite, SWT.NONE);
333
        txtPassword.addKeyListener(new KeyAdapter() {
334
        	@Override
335
        	public void keyPressed(KeyEvent e) {
336
        		if(e.character==SWT.CR){
337
        			connectButtonPressed();
338
        		}
339
        	}
340
        });
341

    
342
        btnConnect = new Button(loginComposite, SWT.FLAT);
343
        btnConnect.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
344
        btnConnect.addSelectionListener(new SelectionAdapter() {
345
			@Override
346
			public void widgetSelected(SelectionEvent e) {
347
				connectButtonPressed();
348
			}
349
		});
350
        btnConnect.setText(Messages.RemotingLoginDialog_LABEL_CONNECT);
351

    
352
        btnRememberMe = new Button(loginComposite, SWT.CHECK);
353
        btnRememberMe.setSelection(true);
354
        GridData gd_btnRememberMe = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1);
355
        btnRememberMe.setLayoutData(gd_btnRememberMe);
356
        btnRememberMe.setText(Messages.RemotingLoginDialog_LABEL_REMEMBER_ME);
357

    
358
        Label lblDefaultLogin = new Label(loginComposite, SWT.NONE);
359
        GridDataFactory.fillDefaults().span(4, 1).align(SWT.TRAIL, SWT.CENTER).applyTo(lblDefaultLogin);
360
        lblDefaultLogin.setText(String.format(Messages.RemotingLoginDialog_DEFAULT_LOGIN, DEFAULT_USER, DEFAULT_PASS));
361

    
362
        styledTxtMessage = new StyledText(remotingComposite, SWT.NONE);
363
        styledTxtMessage.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
364
        styledTxtMessage.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
365
        styledTxtMessage.setFont(SWTResourceManager.getFont(UBUNTU, 12, SWT.BOLD));
366
        styledTxtMessage.setSelectionBackground(SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION_TEXT));
367
        styledTxtMessage.setSelectionForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
368
        styledTxtMessage.setDoubleClickEnabled(false);
369
        styledTxtMessage.setEditable(false);
370
        styledTxtMessage.setWordWrap(true);
371

    
372
        GridData gd_styledTxtMessage = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
373
        gd_styledTxtMessage.exclude = true;
374
        gd_styledTxtMessage.minimumHeight = MESSAGE_HEIGHT;
375

    
376
        styledTxtMessage.setLayoutData(gd_styledTxtMessage);
377

    
378
        xpndblcmpstAdvanced = new ExpandableComposite(remotingComposite, SWT.NONE, ExpandableComposite.TWISTIE);
379
        GridData gd_xpndblcmpstAdvanced = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1);
380
        xpndblcmpstAdvanced.setLayoutData(gd_xpndblcmpstAdvanced);
381
        xpndblcmpstAdvanced.addExpansionListener(new IExpansionListener() {
382
            @Override
383
            public void expansionStateChanged(ExpansionEvent e) {
384
                shlConnect.pack(true);
385
            }
386
            @Override
387
            public void expansionStateChanging(ExpansionEvent e) {
388
            }
389
        });
390
        xpndblcmpstAdvanced.setText(Messages.RemotingLoginDialog_LABEL_ADVANCED);
391
        xpndblcmpstAdvanced.setExpanded(true);
392

    
393
        compAdvanced = new Composite(xpndblcmpstAdvanced, SWT.NONE);
394
        xpndblcmpstAdvanced.setClient(compAdvanced);
395
        compAdvanced.setLayout(new GridLayout(4, false));
396

    
397
        lblPort = new Label(compAdvanced, SWT.CENTER);
398
        lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
399
        lblPort.setText(Messages.RemotingLoginDialog_LABEL_PORT);
400
        lblPort.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
401

    
402
        txtPort = new Text(compAdvanced, SWT.BORDER);
403
        GridData gd_txtPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
404
        gd_txtPort.minimumWidth = 50;
405
        txtPort.setLayoutData(gd_txtPort);
406

    
407
        lblServerVersion = new Label(compAdvanced, SWT.CENTER);
408
        lblServerVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
409
        lblServerVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDMLIB_VERSION);
410
        lblServerVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
411

    
412
        txtServerVersion = new Text(compAdvanced, SWT.BORDER);
413
        txtServerVersion.setEditable(false);
414
        txtServerVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
415
        btnStopServer = new Button(compAdvanced, SWT.FLAT);
416
        btnStopServer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
417
        btnStopServer.addMouseListener(new MouseAdapter() {
418
            @Override
419
            public void mouseUp(MouseEvent e) {
420
                stopManagedServer();
421
            }
422
        });
423
        btnStopServer.setText(Messages.RemotingLoginDialog_LABEL_STOP_MANAGED_SERVER);
424

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

    
430
        txtEditorVersion = new Text(compAdvanced, SWT.BORDER);
431
        txtEditorVersion.setEditable(false);
432
        txtEditorVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
433
//        new Label(compAdvanced, SWT.NONE);
434
//        new Label(compAdvanced, SWT.NONE);
435

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

    
441
        txtServerCDMVersion = new Text(compAdvanced, SWT.BORDER);
442
        txtServerCDMVersion.setEditable(false);
443
        txtServerCDMVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
444
//        new Label(compAdvanced, SWT.NONE);
445
//        new Label(compAdvanced, SWT.NONE);
446

    
447
        lblEditorCDMVersion = new Label(compAdvanced, SWT.CENTER);
448
        lblEditorCDMVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
449
        lblEditorCDMVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDM_VERSION);
450
        lblEditorCDMVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
451

    
452
        txtEditorCDMVersion = new Text(compAdvanced, SWT.BORDER);
453
        txtEditorCDMVersion.setEditable(false);
454
        txtEditorCDMVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
455
    }
456

    
457
	private void connectButtonPressed() {
458
		if(selectedCsii.isLocalhostMgd() && !isSelectedCdmInstanceRunningInManagedServer()) {
459
			startManagedServer();
460
		} else {
461
			connect();
462
			if (CdmStore.isActive() && CdmStore.currentAuthentiationHasOneOfRoles(Role.ROLE_REMOTING)){
463
			    PreferencesUtil.setNomenclaturalCodePreferences();
464
			}
465
		}
466
	}
467

    
468
    private void populateCdmServerCombo() {
469
        Job job = new Job(Messages.RemotingLoginDialog_RETRIEVE_SERVER_INSTANCES) {
470
            @Override
471
            protected IStatus run(IProgressMonitor monitor) {
472
                Display.getDefault().syncExec(new Runnable() {
473
                    @Override
474
                    public void run() {
475
                        for(CdmServerInfo csii : CdmServerInfo.getCdmServers()) {
476
                            csiiMap.put(csii.getName(), csii);
477
                            comboCdmServer.add(csii.getName());
478
                        }
479
                        int serverIndex = -1;
480
                        if(serverName != null) {
481
                            serverIndex = comboCdmServer.indexOf(serverName);
482
                        }
483
                        if(serverIndex == -1) {
484
                            comboCdmServer.select(0);
485
                            autoConnect = false;
486
                        } else {
487
                            comboCdmServer.select(serverIndex);
488
                        }
489
                        CdmRemoteSource devRemoteSource = CdmServerInfo.getDevServerRemoteSource();
490
                        if(devRemoteSource != null) {
491
                            isDevRemoteSource = true;
492
                            String username = System.getProperty("cdm.server.dev.username"); //$NON-NLS-1$
493
                            String password = System.getProperty("cdm.server.dev.password"); //$NON-NLS-1$
494
                            if(username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
495
                                txtLogin.setText(username);
496
                                txtPassword.setText(password);
497
                                CdmStore.connect(devRemoteSource, RemotingLoginDialog.this);
498
                            }
499
                        } else {
500
                            refreshCdmServer();
501
                        }
502
                    }
503
                });
504
                return Status.OK_STATUS;
505
            }
506
        };
507
        job.schedule();
508
    }
509

    
510
    private void refreshCdmServer() {
511
        try{
512
            txtCdmServerStatus.setText(STATUS_CHECKING_AVAILABILITY);
513
            clearOnServerChange();
514
            emptyCredentials();
515
            updateSelectedCdmServer();
516
            Display.getDefault().asyncExec(new Runnable() {
517
                @Override
518
                public void run() {
519
                    checkSelectedCdmServer();
520
                }
521
            });
522
        }
523
        catch(SWTException e){
524
            //catch widget is disposed exception which may occurr if
525
            //dialog is closed but the runnable tries to update
526
        }
527
    }
528

    
529
    private void updateSelectedCdmServer() {
530
        int selIndex = comboCdmServer.getSelectionIndex();
531
        if(selIndex != -1) {
532
            selectedCsii = csiiMap.get(comboCdmServer.getItem(selIndex));
533
        }
534
    }
535

    
536
    private void updatePort() {
537
        txtPort.setText(""); //$NON-NLS-1$
538
        if(selectedCsii != null) {
539
            int port = selectedCsii.getPort();
540
            if(port == CdmServerInfo.NULL_PORT) {
541
                txtPort.setText(CdmServerInfo.NULL_PORT_STRING);
542
            } else {
543
                txtPort.setText(String.valueOf(port));
544
            }
545
        }
546
    }
547

    
548
    private int getPort() {
549
        int port = CdmServerInfo.NULL_PORT;
550
        try {
551
            port = Integer.valueOf(txtPort.getText());
552
        } catch (NumberFormatException nfe) {
553
            if(!CdmServerInfo.NULL_PORT_STRING.equals(txtPort.getText())) {
554
                setMessage(Messages.RemotingLoginDialog_MESSAGE_PORT_SHOULD_BE_INTEGER);
555
            }
556
        }
557
        return port;
558
    }
559

    
560
    private void checkSelectedCdmServer() {
561
        try{
562
            if(selectedCsii != null) {
563
                if(selectedCsii.isLocalhost()) {
564
                    txtPort.setEditable(true);
565
                    txtPort.setEnabled(true);
566
                }
567
                try {
568
                    if(selectedCsii.pingServer()) {
569
                        txtCdmServerStatus.setText(STATUS_AVAILABLE);
570
                        populateCdmInstanceCombo(true);
571
                        String serverVersionTimestamp = generateLastModifiedTooltip(selectedCsii.getCdmlibLastModified());
572
                        txtServerVersion.setText(selectedCsii.getCdmlibServicesVersion() + ":" + serverVersionTimestamp); //$NON-NLS-1$
573
                    } else {
574
                        txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
575
                        comboCdmInstance.removeAll();
576
                        disableCdmInstanceControls("", ""); //$NON-NLS-1$ //$NON-NLS-2$
577
                    }
578
                } catch (CdmServerException | IOException e) {
579
                    txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
580
                    // TODO distinguish java.net.ConnectException: Connection refused, java.net.SocketTimeoutException: Read timed out
581
                    Throwable cause = e;
582
                    if(e instanceof CdmServerException && e.getCause() != null){
583
                        cause = e.getCause();
584
                    }
585
                    String message = Messages.RemotingLoginDialog_CONNECTION_FAILED_MESSAGE;
586
                    if(cause instanceof SocketTimeoutException){
587
                        message = Messages.RemotingLoginDialog_CONNECTION_TIMEOUT_MESSAGE;
588
                    }
589
                    MessagingUtils.warningDialog(Messages.RemotingLoginDialog_CONNECTION_FAILED_TITLE, this,
590
                            message);
591
                    logger.warn(Messages.RemotingLoginDialog_CONNECTION_FAILED_TITLE, e);
592
                }
593
            }
594
            updatePort();
595
        }
596
        catch(SWTException e){
597
            //catch widget is disposed exception which may occurr if
598
            //dialog is closed but the runnable tries to update
599
        }
600
    }
601

    
602
    private void populateCdmInstanceCombo(final boolean forceRefresh) {
603
        comboCdmInstance.removeAll();
604
        comboCdmInstance.setEnabled(false);
605
        btnConnect.setEnabled(false);
606
        txtCdmInstanceStatus.setText(STATUS_RETRIEVING);
607
        txtCdmInstanceStatus.setToolTipText(""); //$NON-NLS-1$
608

    
609
        serverJob = new Job(Messages.RemotingLoginDialog_RETRIEVE_SERVER_INSTANCES) {
610
            @Override
611
            protected IStatus run(IProgressMonitor monitor) {
612
                try {
613
                    if(selectedCsii != null) {
614
                        if(forceRefresh) {
615
                            selectedCsii.refreshInstances();
616
                        }
617
                        final List<CdmInstanceInfo> instances = selectedCsii.getInstances();
618
                        Display.getDefault().asyncExec(new Runnable() {
619
                            @Override
620
                            public void run() {
621
                                if(!instances.isEmpty()) {
622
                                    for(CdmInstanceInfo cdmInstance : instances) {
623
                                        comboCdmInstance.add(cdmInstance.getName());
624
                                    }
625
                                    int instanceIndex = -1;
626
                                    if(instanceName != null) {
627
                                        instanceIndex = comboCdmInstance.indexOf(instanceName);
628
                                    }
629
                                    if(instanceIndex == -1) {
630
                                        comboCdmInstance.select(0);
631
                                        autoConnect = false;
632
                                    } else {
633
                                        comboCdmInstance.select(instanceIndex);
634
                                    }
635
                                    refreshCdmInstance();
636
                                    comboCdmInstance.setEnabled(true);
637
                                    if(autoConnect) {
638
                                        connect();
639
                                    }
640

    
641
                                } else {
642
                                    txtCdmInstanceStatus.setText(STATUS_NO_INSTANCES);
643
                                    btnConnect.setEnabled(false);
644
                                }
645
                            }
646
                        });
647
                    }
648
                } catch (final CdmServerException e) {
649
                    MessagingUtils.warn(getClass(), e);
650
                    Display.getDefault().asyncExec(new Runnable() {
651
                        @Override
652
                        public void run() {
653
                            disableCdmInstanceControls(STATUS_NOT_AVAILABLE, e.getMessage());
654
                        }
655
                    });
656
                }
657
                return Status.OK_STATUS;
658
            }
659
        };
660

    
661
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE) && !isDevRemoteSource) {
662
            // Start the Job
663
            serverJob.schedule();
664
        }
665
    }
666

    
667
    private void disableCdmInstanceControls(String cdmInstanceStatus, String tooltip) {
668
        txtCdmInstanceStatus.setText(cdmInstanceStatus);
669
        txtCdmInstanceStatus.setToolTipText(tooltip);
670
        comboCdmInstance.setEnabled(false);
671
        btnConnect.setEnabled(false);
672

    
673
    }
674

    
675
    private void refreshCdmInstance() {
676
        txtCdmInstanceStatus.setText(STATUS_CHECKING_AVAILABILITY);
677
        clearOnInstanceChange();
678
        updateSelectedCdmInstance();
679
        checkSelectedCdmInstance();
680
        updateManagedServerControls();
681
    }
682

    
683
    private void updateSelectedCdmInstance() {
684
        int selIndex = comboCdmInstance.getSelectionIndex();
685
        if(selIndex != -1) {
686
            selectedCdmInstance = selectedCsii.getInstanceFromName(comboCdmInstance.getItem(selIndex));
687

    
688
            if(loadLoginPrefs) {
689
                readPrefCredentials();
690
            }
691
        }
692
    }
693

    
694
    private void updateManagedServerControls() {
695
        if(selectedCsii.isLocalhostMgd()) {
696
            if(isSelectedCdmInstanceRunningInManagedServer()) {
697
                txtCdmInstanceStatus.setText(STATUS_STARTED);
698
            } else {
699
                txtCdmInstanceStatus.setText(STATUS_NOT_STARTED);
700
            }
701
            btnConnect.setEnabled(true);
702
            selectedCsii.setPort(getManagedServerPort());
703
            updatePort();
704
        }
705

    
706
        if(isManagedServerRunning()) {
707
            btnStopServer.setEnabled(true);
708
        } else {
709
            btnStopServer.setEnabled(false);
710
        }
711
    }
712

    
713
    private boolean isManagedServerRunning() {
714
        return CdmStore.getManagedServer() != null && CdmStore.getManagedServer().isAlive();
715
    }
716

    
717
    private boolean isSelectedCdmInstanceRunningInManagedServer() {
718
        return CdmStore.getManagedServer() != null &&
719
                CdmStore.getManagedServer().isAlive() &&
720
                selectedCsii.isLocalhostMgd() &&
721
                CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName());
722
    }
723

    
724
    private void startManagedServer() {
725
        if(isManagedServerRunning()) {
726
            if(CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())) {
727
                return;
728
            } else {
729
                Display.getDefault().syncExec(new Runnable() {
730
                    @Override
731
                    public void run() {
732
                        stopManagedServer();
733
                    }
734
                });
735
            }
736
        }
737

    
738
        Job job = new Job(Messages.RemotingLoginDialog_JOB_SERVER_LAUNCH) {
739

    
740
            @Override
741
            public IStatus run(IProgressMonitor monitor) {
742
                String mgdServerConfigFileName = "mgd.datasources.xml"; //$NON-NLS-1$
743
                String config = CdmServerUtils.convertEditorToServerConfig();
744
                int maxUnits = 50;
745
                monitor.beginTask(Messages.RemotingLoginDialog_TASK_LAUNCHING_SERVER, maxUnits);
746
                try {
747
                    monitor.subTask(String.format(Messages.RemotingLoginDialog_GENERATING_CONFIG_FILE, selectedCdmInstance.getName()));
748
                    File managedServerConfigFile = CdmServerUtils.writeManagedServerConfig(config, mgdServerConfigFileName);
749
                    monitor.worked(1);
750
                    boolean forceSchemaCreate = CdmStore.getManagedServer() != null
751
                            && CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())
752
                            && CdmStore.getManagedServer().isForceSchemaCreate();
753
                    CdmStore.setManagedServer(new CdmServer(selectedCdmInstance.getName(), managedServerConfigFile));
754
                    CdmStore.getManagedServer().setForceSchemaCreate(forceSchemaCreate);
755
                    monitor.subTask(Messages.RemotingLoginDialog_STARTING_MGD_SERVER);
756
                    CdmStore.getManagedServer().start(false, RemotingLoginDialog.this);
757
                    int serverUnits = 0;
758

    
759
                    // the following loop is a 'fake' progress monitoring where the progress
760
                    // bar is advanced by one unit every second until maxUnits -2
761
                    while(!CdmStore.getManagedServer().isStarted() && !CdmStore.getManagedServer().isFailed()) {
762
                        if(serverUnits < maxUnits - 2) {
763
                            try {
764
                                Thread.sleep(1000);
765
                            } catch (InterruptedException e) {
766
                            }
767
                            monitor.worked(1);
768
                            serverUnits++;
769
                        }
770
                    }
771
                    Display.getDefault().asyncExec(new Runnable() {
772
                        @Override
773
                        public void run() {
774
                                hide(false);
775
                                updateManagedServerControls();
776
                                connect();
777
                            }
778
                    });
779
                } catch (IOException ioe) {
780
                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_GENERATING_CONFIG_FILE,
781
                            this,
782
                            ioe.getMessage(),
783
                            TaxeditorStorePlugin.PLUGIN_ID,
784
                            ioe,
785
                            true);
786
                } catch (CdmEmbeddedServerException cese) {
787
                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STARTING_SERVER,
788
                            this,
789
                            cese.getMessage(),
790
                            TaxeditorStorePlugin.PLUGIN_ID,
791
                            cese,
792
                            true);
793
                } finally {
794
                    monitor.done();
795
                }
796
                // NOTE: Errors thrown during server startup are passed to the handleError() implementation
797
                // TODO: is the above catch clause for CDMEmbeddedServerException still valuable?
798

    
799
                return Status.OK_STATUS;
800
            }
801
        };
802

    
803
        // configure the job
804
        job.setProperty(IProgressConstants.KEEP_PROPERTY, true);
805
        job.setUser(true);
806
        // schedule job
807
        hide(true);
808
        job.schedule();
809
    }
810

    
811
    @Override
812
    public void handleError(final Throwable t) {
813

    
814
        if(CdmStore.getManagedServer().isFailed() && CdmStore.getManagedServer().isPotentiallyMissingSchema()) {
815
            CdmStore.getManagedServer().setForceSchemaCreate(true);
816
            // we are in a separate thread here, thus update the screen via
817
            Display.getDefault().asyncExec(new Runnable() {
818
                @Override
819
                public void run() {
820
                    btnConnect.setEnabled(true);
821
                    btnConnect.setText("Create Schema");
822
                    btnConnect.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_RED));
823
                    btnConnect.requestLayout();
824
                }
825
             });
826
        } else {
827
            Display.getDefault().syncExec(new Runnable() {
828
                @Override
829
                public void run() {
830
                    serverJob.cancel();
831

    
832
                    String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
833
                    String  message = t.getMessage();
834

    
835
                    MessagingUtils.errorDialog(title,
836
                            this,
837
                            message,
838
                            TaxeditorStorePlugin.PLUGIN_ID,
839
                            t,
840
                            true);
841
                }
842
            });
843
        }
844
    }
845

    
846
    private void stopManagedServer() {
847
        try {
848
            CdmStore.getManagedServer().stop();
849
        } catch (Exception e) {
850
            MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STOPPING_SERVER,
851
                    this,
852
                    String.format(Messages.RemotingLoginDialog_COULD_NOT_STOP_SERVER, CdmStore.getManagedServer().getPort()),
853
                    TaxeditorStorePlugin.PLUGIN_ID,
854
                    e,
855
                    true);
856
        }
857
        CdmStore.setManagedServer(null);
858
        updateManagedServerControls();
859
    }
860

    
861
    private int getManagedServerPort() {
862
        return CdmStore.getManagedServer() == null ? CdmServerInfo.NULL_PORT : CdmStore.getManagedServer().getPort();
863
    }
864

    
865
    private void checkSelectedCdmInstance() {
866
        boolean available = false;
867
        String status = STATUS_NOT_AVAILABLE;
868
        String message = null;
869

    
870
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE)) {
871
            try {
872
                if(selectedCsii.pingInstance(selectedCdmInstance, getPort())) {
873
                    status = STATUS_AVAILABLE;
874
                    available = true;
875
                } else {
876
                    status = STATUS_NOT_AVAILABLE;
877
                    available = false;
878
                }
879

    
880
                if(available) {
881
                    txtServerCDMVersion.setText(selectedCsii.getCdmRemoteSource(selectedCdmInstance, getPort()).getDbSchemaVersion());
882
                    int compareDbSchemaVersion = selectedCsii.compareDbSchemaVersion(selectedCdmInstance, getPort());
883
                    int compareCdmlibServicesVersion = 0;
884
                    boolean disableServicesApiTimestampCheck =
885
                            PreferencesUtil.getBooleanValue((IPreferenceKeys.DISABLE_SERVICES_API_TIMESTAMP_CHECK));
886
                    if(!disableServicesApiTimestampCheck) {
887
                        compareCdmlibServicesVersion = selectedCsii.compareCdmlibServicesVersion();
888
                    }
889
                    if(compareDbSchemaVersion > 0 || compareCdmlibServicesVersion > 0) {
890
                        status =  STATUS_NOT_COMPATIBLE;
891
                        available = false;
892
                        message = MESG_COMPATIBLE_EDITOR_OLD;
893
                    } else if(compareDbSchemaVersion < 0 || compareCdmlibServicesVersion < 0) {
894
                        status = STATUS_NOT_COMPATIBLE;
895
                        available = false;
896
                        message = MESG_COMPATIBLE_SERVER_OLD;
897
                    } else {
898
                        status =  STATUS_AVAILABLE;
899
                        available = true;
900
                        message = ""; //$NON-NLS-1$
901
                    }
902
                }
903
            } catch (Exception e) {
904
                txtCdmInstanceStatus.setToolTipText(e.getMessage());
905
            } finally {
906
                btnConnect.setEnabled(available);
907
                txtCdmInstanceStatus.setText(status);
908
                if(!StringUtils.isBlank(message)) {
909
                    setMessage(message);
910
                }
911
            }
912
        }
913
    }
914

    
915
    private void connect() {
916
        checkSelectedCdmInstance();
917

    
918
        if(!txtCdmInstanceStatus.getText().equals(STATUS_AVAILABLE)) {
919
            return;
920
        }
921

    
922
        ICdmRemoteSource source = selectedCsii.getCdmRemoteSource(selectedCdmInstance, getPort());
923

    
924
        if(!validateLogin(source)) {
925
            return;
926
        }
927

    
928
        try {
929
            CdmStore.connect(source, this);
930
        } catch (Exception e) {
931
            // Do not expect anything to go wrong at this point, so we throw a runtime exception
932
            // if any problems
933
            throw new RuntimeException(e);
934
        }
935
    }
936

    
937
    public boolean isRememberMe() {
938
        return btnRememberMe.getSelection();
939
    }
940

    
941
    private void persistPrefLastServerInstance() {
942
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
943
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
944

    
945
        lastServerInstancePrefs.put(LAST_SERVER_KEY, selectedCsii.getName());
946
        lastServerInstancePrefs.put(LAST_INSTANCE_KEY, selectedCdmInstance.getName());
947

    
948
        flushPreferences(lastServerInstancePrefs);
949
    }
950

    
951
    private void persistPrefCredentials() {
952
         IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
953
         Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
954
         credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
955
         credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
956
         flushPreferences(credentialsPrefs);
957
    }
958

    
959
    private void removePrefCredentials() {
960
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
961
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
962
        credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
963
        credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
964
        removePreferences(credentialsPrefs);
965
    }
966

    
967
    private void removePreferences(Preferences prefs) {
968
        try {
969
            prefs.removeNode();
970
        } catch (BackingStoreException bse) {
971
            setMessage(bse.getMessage());
972
        }
973
    }
974

    
975
    private void flushPreferences(Preferences prefs) {
976
        try {
977
            prefs.flush();
978
        } catch (BackingStoreException bse) {
979
            setMessage(bse.getMessage());
980
        }
981
    }
982

    
983
    private void readPrefCredentials() {
984
        String username, password;
985
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
986
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
987
        username = credentialsPrefs.get(getUsernamePrefKey(), ""); //$NON-NLS-1$
988
        txtLogin.setText(username);
989
        password = credentialsPrefs.get(getPasswordPrefKey(),""); //$NON-NLS-1$
990
        txtPassword.setText(password);
991
        if(username.isEmpty() || password.isEmpty()) {
992
            autoConnect = false;
993
        }
994
    }
995

    
996
    private void readPrefLastServerInstance() {
997
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
998
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
999

    
1000
        serverName = lastServerInstancePrefs.get(LAST_SERVER_KEY, null);
1001
        instanceName = lastServerInstancePrefs.get(LAST_INSTANCE_KEY, null);
1002
    }
1003

    
1004
    private void emptyCredentials() {
1005
        txtLogin.setText(""); //$NON-NLS-1$
1006
        txtPassword.setText(""); //$NON-NLS-1$
1007
    }
1008

    
1009
    private String getUsernamePrefKey() {
1010
        return selectedCsii.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + USERNAME_SUFFIX;
1011
    }
1012

    
1013
    private String getPasswordPrefKey() {
1014
        return selectedCsii.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + PASSWORD_SUFFIX;
1015
    }
1016

    
1017
    private boolean validateLogin(ICdmRemoteSource remoteSource) {
1018
        if(getUsername() == null || getUsername().isEmpty()) {
1019
            setMessage(Messages.RemotingLoginDialog_LOGIN_CANNOT_BE_EMPTY);
1020
            return false;
1021
        }
1022
        if(getPassword() == null || getPassword().isEmpty()) {
1023
            setMessage(Messages.RemotingLoginDialog_PASSWORD_CANNOT_BE_EMPTY);
1024
            return false;
1025
        }
1026

    
1027
        try {
1028
            IUserService userService = CdmApplicationRemoteConfiguration.getUserService(remoteSource);
1029
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(getUsername(), getPassword());
1030
            CdmApplicationRemoteConfiguration.getAuthenticationManager(userService).authenticate(token);
1031
        } catch(BadCredentialsException e){
1032
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1033
            return false;
1034
        } catch(LockedException e){
1035
            setMessage(LoginManager.ACCOUNT_LOCKED_MESSAGE);
1036
            return false;
1037
        } catch(IllegalArgumentException e){
1038
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1039
            return false;
1040
        }
1041
        return true;
1042
    }
1043

    
1044
    public String getUsername() {
1045
        return txtLogin.getText();
1046
    }
1047

    
1048
    public String getPassword() {
1049
        return txtPassword.getText();
1050
    }
1051

    
1052
    public void setMessage(String message) {
1053
        if(message != null && !message.isEmpty()) {
1054
//            if(message.length() > 50) {
1055
//                styledTxtMessage.setToolTipText(message);
1056
//                message = message.substring(0,50) + "..."; //$NON-NLS-1$
1057
//            }
1058
            styledTxtMessage.setText(message);
1059
            styledTxtMessage.setVisible(true);
1060
            ((GridData)styledTxtMessage.getLayoutData()).exclude = false;
1061
//            shlConnect.setMinimumSize(MIN_WIDTH, getHeightWithoutMessage() + MESSAGE_HEIGHT);
1062
            shlConnect.pack(true);
1063
        } else {
1064
            if (!styledTxtMessage.isDisposed()){
1065
                styledTxtMessage.setText(""); //$NON-NLS-1$
1066
                styledTxtMessage.setVisible(false);
1067
                ((GridData)styledTxtMessage.getLayoutData()).exclude = true;
1068
            }
1069
            if(!shlConnect.isDisposed()){
1070
                shlConnect.pack(true);
1071
            }
1072
        }
1073
        if (!remotingComposite.isDisposed()){
1074
            remotingComposite.layout();
1075
        }
1076
    }
1077

    
1078
//    private int getHeightWithoutMessage() {
1079
//        if(xpndblcmpstAdvanced.isExpanded()) {
1080
//            return MIN_EXP_HEIGHT;
1081
//        } else {
1082
//            return MIN_HEIGHT;
1083
//        }
1084
//    }
1085

    
1086
    public void hide(boolean isHidden) {
1087
        if (!shlConnect.isDisposed()){
1088
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1089
                shlConnect.setVisible(!isHidden);
1090
            }
1091
        }
1092
    }
1093

    
1094
    public void dispose() {
1095
        if (!shlConnect.isDisposed()){
1096
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1097
                shlConnect.dispose();
1098
            }
1099
        }
1100
    }
1101

    
1102
    public void onComplete() {
1103
        Display.getDefault().asyncExec(new Runnable() {
1104
            @Override
1105
            public void run() {
1106
                if(selectedCdmInstance!=null){
1107
                    if(isRememberMe()) {
1108
                        persistPrefCredentials();
1109
                    }else{
1110
                        removePrefCredentials();
1111
                    }
1112
                    persistPrefLastServerInstance();
1113
                }
1114
                dispose();
1115
            }
1116
        });
1117
    }
1118

    
1119
    private String generateLastModifiedTooltip(String cdmlibLastModified) {
1120
        if(StringUtils.isBlank(cdmlibLastModified)) {
1121
            return ""; //$NON-NLS-1$
1122
        }
1123
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.z"); //$NON-NLS-1$
1124
        Date cdmlibLastModifiedDate;
1125
        String cdmlibLastModifiedTimestamp = ""; //$NON-NLS-1$
1126

    
1127
        cdmlibLastModifiedDate = new Date(Long.valueOf(cdmlibLastModified));
1128
        cdmlibLastModifiedTimestamp = sdf.format(cdmlibLastModifiedDate);
1129

    
1130
        return cdmlibLastModifiedTimestamp;
1131
    }
1132

    
1133
    private void setEditorInfo() {
1134
        txtEditorCDMVersion.setText(CdmMetaData.getDbSchemaVersion());
1135
        String editorVersionTimestamp = generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified());
1136
        txtEditorVersion.setText(CdmApplicationState.getCdmlibVersion() + ":" + editorVersionTimestamp); //$NON-NLS-1$
1137
    }
1138

    
1139
    private void clearOnServerChange() {
1140
        setMessage(""); //$NON-NLS-1$
1141
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1142
        txtServerVersion.setText(""); //$NON-NLS-1$
1143
        txtServerVersion.setToolTipText(""); //$NON-NLS-1$
1144
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1145
        comboCdmInstance.removeAll();
1146
        txtCdmInstanceStatus.setText(""); //$NON-NLS-1$
1147
        txtPort.setEditable(false);
1148
        txtPort.setEnabled(false);
1149
    }
1150

    
1151
    private void clearOnInstanceChange() {
1152
        setMessage(""); //$NON-NLS-1$
1153
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1154
    }
1155
}
(5-5/8)