Project

General

Profile

Download (49 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
        addEmptyCells(2);
434

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

    
440
        txtServerCDMVersion = new Text(compAdvanced, SWT.BORDER);
441
        txtServerCDMVersion.setEditable(false);
442
        txtServerCDMVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER , true, false, 1, 1));
443
        addEmptyCells(2);
444

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

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

    
455
    @SuppressWarnings("unused")
456
    private void addEmptyCells(int cnt) {
457
        for (int i = 0; i < cnt; i++) {
458
            new Label(compAdvanced, SWT.NONE);
459
        }
460
    }
461

    
462
	private void connectButtonPressed() {
463
		if(selectedCsii.isLocalhostMgd() && !isSelectedCdmInstanceRunningInManagedServer()) {
464
			startManagedServer();
465
		} else {
466
			connect();
467
			if (CdmStore.isActive() && CdmStore.currentAuthentiationHasOneOfRoles(Role.ROLE_REMOTING)){
468
			    PreferencesUtil.setNomenclaturalCodePreferences();
469
			}
470
		}
471
	}
472

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

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

    
534
    private void updateSelectedCdmServer() {
535
        int selIndex = comboCdmServer.getSelectionIndex();
536
        if(selIndex != -1) {
537
            selectedCsii = csiiMap.get(comboCdmServer.getItem(selIndex));
538
        }
539
    }
540

    
541
    private void updatePort() {
542
        txtPort.setText(""); //$NON-NLS-1$
543
        if(selectedCsii != null) {
544
            int port = selectedCsii.getPort();
545
            if(port == CdmServerInfo.NULL_PORT) {
546
                txtPort.setText(CdmServerInfo.NULL_PORT_STRING);
547
            } else {
548
                txtPort.setText(String.valueOf(port));
549
            }
550
        }
551
    }
552

    
553
    private int getPort() {
554
        int port = CdmServerInfo.NULL_PORT;
555
        try {
556
            port = Integer.valueOf(txtPort.getText());
557
        } catch (NumberFormatException nfe) {
558
            if(!CdmServerInfo.NULL_PORT_STRING.equals(txtPort.getText())) {
559
                setMessage(Messages.RemotingLoginDialog_MESSAGE_PORT_SHOULD_BE_INTEGER);
560
            }
561
        }
562
        return port;
563
    }
564

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

    
607
    private void populateCdmInstanceCombo(final boolean forceRefresh) {
608
        comboCdmInstance.removeAll();
609
        comboCdmInstance.setEnabled(false);
610
        btnConnect.setEnabled(false);
611
        txtCdmInstanceStatus.setText(STATUS_RETRIEVING);
612
        txtCdmInstanceStatus.setToolTipText(""); //$NON-NLS-1$
613

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

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

    
666
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE) && !isDevRemoteSource) {
667
            // Start the Job
668
            serverJob.schedule();
669
        }
670
    }
671

    
672
    private void disableCdmInstanceControls(String cdmInstanceStatus, String tooltip) {
673
        txtCdmInstanceStatus.setText(cdmInstanceStatus);
674
        txtCdmInstanceStatus.setToolTipText(tooltip);
675
        comboCdmInstance.setEnabled(false);
676
        btnConnect.setEnabled(false);
677

    
678
    }
679

    
680
    private void refreshCdmInstance() {
681
        txtCdmInstanceStatus.setText(STATUS_CHECKING_AVAILABILITY);
682
        clearOnInstanceChange();
683
        updateSelectedCdmInstance();
684
        checkSelectedCdmInstance();
685
        updateManagedServerControls();
686
    }
687

    
688
    private void updateSelectedCdmInstance() {
689
        int selIndex = comboCdmInstance.getSelectionIndex();
690
        if(selIndex != -1) {
691
            selectedCdmInstance = selectedCsii.getInstanceFromName(comboCdmInstance.getItem(selIndex));
692

    
693
            if(loadLoginPrefs) {
694
                readPrefCredentials();
695
            }
696
        }
697
    }
698

    
699
    private void updateManagedServerControls() {
700
        if(selectedCsii.isLocalhostMgd()) {
701
            if(isSelectedCdmInstanceRunningInManagedServer()) {
702
                txtCdmInstanceStatus.setText(STATUS_STARTED);
703
            } else {
704
                txtCdmInstanceStatus.setText(STATUS_NOT_STARTED);
705
            }
706
            btnConnect.setEnabled(true);
707
            selectedCsii.setPort(getManagedServerPort());
708
            updatePort();
709
        }
710

    
711
        if(isManagedServerRunning()) {
712
            btnStopServer.setEnabled(true);
713
        } else {
714
            btnStopServer.setEnabled(false);
715
        }
716
    }
717

    
718
    private boolean isManagedServerRunning() {
719
        return CdmStore.getManagedServer() != null && CdmStore.getManagedServer().isAlive();
720
    }
721

    
722
    private boolean isSelectedCdmInstanceRunningInManagedServer() {
723
        return CdmStore.getManagedServer() != null &&
724
                CdmStore.getManagedServer().isAlive() &&
725
                selectedCsii.isLocalhostMgd() &&
726
                CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName());
727
    }
728

    
729
    private void startManagedServer() {
730
        if(isManagedServerRunning()) {
731
            if(CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())) {
732
                return;
733
            } else {
734
                Display.getDefault().syncExec(new Runnable() {
735
                    @Override
736
                    public void run() {
737
                        stopManagedServer();
738
                    }
739
                });
740
            }
741
        }
742

    
743
        Job job = new Job(Messages.RemotingLoginDialog_JOB_SERVER_LAUNCH) {
744

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

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

    
804
                return Status.OK_STATUS;
805
            }
806
        };
807

    
808
        // configure the job
809
        job.setProperty(IProgressConstants.KEEP_PROPERTY, true);
810
        job.setUser(true);
811
        // schedule job
812
        hide(true);
813
        job.schedule();
814
    }
815

    
816
    @Override
817
    public void handleError(final Throwable t) {
818

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

    
837
                    String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
838
                    String  message = t.getMessage();
839

    
840
                    MessagingUtils.errorDialog(title,
841
                            this,
842
                            message,
843
                            TaxeditorStorePlugin.PLUGIN_ID,
844
                            t,
845
                            true);
846
                }
847
            });
848
        }
849
    }
850

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

    
866
    private int getManagedServerPort() {
867
        return CdmStore.getManagedServer() == null ? CdmServerInfo.NULL_PORT : CdmStore.getManagedServer().getPort();
868
    }
869

    
870
    private void checkSelectedCdmInstance() {
871
        boolean available = false;
872
        String status = STATUS_NOT_AVAILABLE;
873
        String message = null;
874

    
875
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE)) {
876
            try {
877
                if(selectedCsii.pingInstance(selectedCdmInstance, getPort())) {
878
                    status = STATUS_AVAILABLE;
879
                    available = true;
880
                } else {
881
                    status = STATUS_NOT_AVAILABLE;
882
                    available = false;
883
                }
884

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

    
920
    private void connect() {
921
        checkSelectedCdmInstance();
922

    
923
        if(!txtCdmInstanceStatus.getText().equals(STATUS_AVAILABLE)) {
924
            return;
925
        }
926

    
927
        ICdmRemoteSource source = selectedCsii.getCdmRemoteSource(selectedCdmInstance, getPort());
928

    
929
        if(!validateLogin(source)) {
930
            return;
931
        }
932

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

    
942
    public boolean isRememberMe() {
943
        return btnRememberMe.getSelection();
944
    }
945

    
946
    private void persistPrefLastServerInstance() {
947
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
948
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
949

    
950
        lastServerInstancePrefs.put(LAST_SERVER_KEY, selectedCsii.getName());
951
        lastServerInstancePrefs.put(LAST_INSTANCE_KEY, selectedCdmInstance.getName());
952

    
953
        flushPreferences(lastServerInstancePrefs);
954
    }
955

    
956
    private void persistPrefCredentials() {
957
         IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
958
         Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
959
         credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
960
         credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
961
         flushPreferences(credentialsPrefs);
962
    }
963

    
964
    private void removePrefCredentials() {
965
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
966
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
967
        credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
968
        credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
969
        removePreferences(credentialsPrefs);
970
    }
971

    
972
    private void removePreferences(Preferences prefs) {
973
        try {
974
            prefs.removeNode();
975
        } catch (BackingStoreException bse) {
976
            setMessage(bse.getMessage());
977
        }
978
    }
979

    
980
    private void flushPreferences(Preferences prefs) {
981
        try {
982
            prefs.flush();
983
        } catch (BackingStoreException bse) {
984
            setMessage(bse.getMessage());
985
        }
986
    }
987

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

    
1001
    private void readPrefLastServerInstance() {
1002
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1003
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
1004

    
1005
        serverName = lastServerInstancePrefs.get(LAST_SERVER_KEY, null);
1006
        instanceName = lastServerInstancePrefs.get(LAST_INSTANCE_KEY, null);
1007
    }
1008

    
1009
    private void emptyCredentials() {
1010
        txtLogin.setText(""); //$NON-NLS-1$
1011
        txtPassword.setText(""); //$NON-NLS-1$
1012
    }
1013

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

    
1018
    private String getPasswordPrefKey() {
1019
        return selectedCsii.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + PASSWORD_SUFFIX;
1020
    }
1021

    
1022
    private boolean validateLogin(ICdmRemoteSource remoteSource) {
1023
        if(getUsername() == null || getUsername().isEmpty()) {
1024
            setMessage(Messages.RemotingLoginDialog_LOGIN_CANNOT_BE_EMPTY);
1025
            return false;
1026
        }
1027
        if(getPassword() == null || getPassword().isEmpty()) {
1028
            setMessage(Messages.RemotingLoginDialog_PASSWORD_CANNOT_BE_EMPTY);
1029
            return false;
1030
        }
1031

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

    
1049
    public String getUsername() {
1050
        return txtLogin.getText();
1051
    }
1052

    
1053
    public String getPassword() {
1054
        return txtPassword.getText();
1055
    }
1056

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

    
1083
//    private int getHeightWithoutMessage() {
1084
//        if(xpndblcmpstAdvanced.isExpanded()) {
1085
//            return MIN_EXP_HEIGHT;
1086
//        } else {
1087
//            return MIN_HEIGHT;
1088
//        }
1089
//    }
1090

    
1091
    public void hide(boolean isHidden) {
1092
        if (!shlConnect.isDisposed()){
1093
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1094
                shlConnect.setVisible(!isHidden);
1095
            }
1096
        }
1097
    }
1098

    
1099
    public void dispose() {
1100
        if (!shlConnect.isDisposed()){
1101
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1102
                shlConnect.dispose();
1103
            }
1104
        }
1105
    }
1106

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

    
1124
    private String generateLastModifiedTooltip(String cdmlibLastModified) {
1125
        if(StringUtils.isBlank(cdmlibLastModified)) {
1126
            return ""; //$NON-NLS-1$
1127
        }
1128
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.z"); //$NON-NLS-1$
1129
        Date cdmlibLastModifiedDate;
1130
        String cdmlibLastModifiedTimestamp = ""; //$NON-NLS-1$
1131

    
1132
        cdmlibLastModifiedDate = new Date(Long.valueOf(cdmlibLastModified));
1133
        cdmlibLastModifiedTimestamp = sdf.format(cdmlibLastModifiedDate);
1134

    
1135
        return cdmlibLastModifiedTimestamp;
1136
    }
1137

    
1138
    private void setEditorInfo() {
1139
        txtEditorCDMVersion.setText(CdmMetaData.getDbSchemaVersion());
1140
        String editorVersionTimestamp = generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified());
1141
        txtEditorVersion.setText(CdmApplicationState.getCdmlibVersion() + ":" + editorVersionTimestamp); //$NON-NLS-1$
1142
    }
1143

    
1144
    private void clearOnServerChange() {
1145
        setMessage(""); //$NON-NLS-1$
1146
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1147
        txtServerVersion.setText(""); //$NON-NLS-1$
1148
        txtServerVersion.setToolTipText(""); //$NON-NLS-1$
1149
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1150
        comboCdmInstance.removeAll();
1151
        txtCdmInstanceStatus.setText(""); //$NON-NLS-1$
1152
        txtPort.setEditable(false);
1153
        txtPort.setEnabled(false);
1154
    }
1155

    
1156
    private void clearOnInstanceChange() {
1157
        setMessage(""); //$NON-NLS-1$
1158
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1159
    }
1160
}
(5-5/8)