Project

General

Profile

Download (56.7 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.remote.ui;
10

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

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

    
58
import eu.etaxonomy.cdm.api.application.CdmApplicationRemoteConfiguration;
59
import eu.etaxonomy.cdm.api.application.CdmApplicationState;
60
import eu.etaxonomy.cdm.api.service.IUserService;
61
import eu.etaxonomy.cdm.common.CdmUtils;
62
import eu.etaxonomy.cdm.config.CdmSourceException;
63
import eu.etaxonomy.cdm.config.ICdmSource;
64
import eu.etaxonomy.cdm.model.metadata.CdmMetaData;
65
import eu.etaxonomy.cdm.persistence.permission.Role;
66
import eu.etaxonomy.taxeditor.l10n.Messages;
67
import eu.etaxonomy.taxeditor.model.MessagingUtils;
68
import eu.etaxonomy.taxeditor.preference.IPreferenceKeys;
69
import eu.etaxonomy.taxeditor.preference.PreferencesUtil;
70
import eu.etaxonomy.taxeditor.remote.store.CdmStoreRemote;
71
import eu.etaxonomy.taxeditor.remoting.server.CdmServerException;
72
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteLocalhostSource;
73
import eu.etaxonomy.taxeditor.remoting.source.CdmServerInfo;
74
import eu.etaxonomy.taxeditor.remoting.source.CdmServerInfo.CdmInstanceInfo;
75
import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
76
import eu.etaxonomy.taxeditor.store.CdmStore;
77
import eu.etaxonomy.taxeditor.store.LoginManager;
78
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
79
import eu.etaxonomy.taxeditor.workbench.datasource.ICDMServerError;
80
import eu.etaxonomy.taxeditor.workbench.datasource.IRemotingLoginDialog;
81

    
82

    
83

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

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

    
92
//    private static final String DEFAULT_PASS = "00000"; //$NON-NLS-1$
93
//    private static final String DEFAULT_USER = "admin"; //$NON-NLS-1$
94
//
95
//    private final static String STATUS_AVAILABLE = Messages.RemotingLoginDialog_STATUS_AVAILABLE;
96
//    private final static String STATUS_NOT_AVAILABLE = Messages.RemotingLoginDialog_STATUS_NOT_AVAILABLE;
97
//    private final static String STATUS_STARTED = Messages.RemotingLoginDialog_STATUS_STARTED;
98
//    private final static String STATUS_NOT_STARTED = Messages.RemotingLoginDialog_STATUS_NOT_STARTED;
99
//    private final static String STATUS_RETRIEVING = Messages.RemotingLoginDialog_STATUS_RETRIEVING;
100
//    private final static String STATUS_CHECKING_AVAILABILITY = Messages.RemotingLoginDialog_STATUS_CHECKING;
101
//    private final static String STATUS_NO_INSTANCES = Messages.RemotingLoginDialog_STATUS_NO_INSTANCES_FOUND;
102
//    private final static String STATUS_NOT_COMPATIBLE = Messages.RemotingLoginDialog_STATUS_NOT_COMPATIBLE;
103
//
104
//    private final static String MESG_COMPATIBLE_EDITOR_OLD = Messages.RemotingLoginDialog_UPDATE_EDITOR;
105
//    private final static String MESG_COMPATIBLE_SERVER_OLD = Messages.RemotingLoginDialog_CHOOSE_COMPATIBLE_CDM_SERVER;
106
//    private final static String MESG_SCHEMA_MISSING = Messages.RemotingLoginDialog_SCHEMA_MISSING;
107
//    private final static String MESG_NO_SCHEMA = Messages.RemotingLoginDialog_NO_SCHEMA;
108
//
109
//    private final static String LABEL_CONNECT = Messages.RemotingLoginDialog_LABEL_CONNECT;
110
//    private final static String LABEL_CREATE_SCHEMA = Messages.RemotingLoginDialog_LABEL_CREATE_SCHEMA;
111
//    private final static String LABEL_UPDATE_SCHEMA_VERSION = Messages.RemotingLoginDialog_LABEL_UPDATE_SCHEMA_VERSION;
112
//    private final static String MESG_UPDATE_SCHEMA_VERSION = Messages.RemotingLoginDialog_MSG_UPDATE_SCHEMA_VERSION;
113
//
114
//    private static final int BTN_COLOR_ATTENTION = SWT.COLOR_RED;
115
//
116
//    private final static String STORE_PREFERENCES_NODE = "eu.etaxonomy.taxeditor.store"; //$NON-NLS-1$
117
//
118
//    private final static String LOGIN_NODE = "login"; //$NON-NLS-1$
119
//    private final static String USERNAME_SUFFIX = "_username"; //$NON-NLS-1$
120
//    private final static String PASSWORD_SUFFIX = "_password"; //$NON-NLS-1$
121
//
122
//    private final static String LAST_SERVER_INSTANCE_NODE = "lastServerInstance"; //$NON-NLS-1$
123
//    private final static String LAST_SERVER_KEY = "lastServerKey"; //$NON-NLS-1$
124
//    private final static String LAST_INSTANCE_KEY = "lastInstanceKey"; //$NON-NLS-1$
125

    
126
    protected Shell shlConnect;
127
    private Text txtCdmServerStatus;
128
    private Text txtCdmInstanceStatus;
129
    private Combo comboCdmServer;
130
    private Combo comboCdmInstance;
131
    private Button btnConnect;
132

    
133
    private Composite remotingComposite;
134
    private Button btnCdmServerRefresh;
135
    private Button btnCdmInstanceRefresh;
136
    private Button btnStopServer;
137
    private Composite loginComposite;
138
    private Label lblLogin;
139
    private Text txtLogin;
140
    private Label lblPassword;
141
    private Text txtPassword;
142
    private Button btnRememberMe;
143
    private Label lblDefaultLogin;
144
    private Composite compAdvanced;
145
    private Label lblPort;
146
    private Text txtPort;
147
    private Label lblServerCdmlibVersion;
148
    private Text txtServerCdmlibVersion;
149
    private ExpandableComposite expandableCompositeAdvanced;
150
    private StyledText styledTxtMessage;
151

    
152
    private Label lblEditorCdmlibVersion;
153
    private Text txtEditorCdmlibVersion;
154
    private Label lblServerSchemaVersion;
155
    private Text txtServerSchemaVersion;
156
    private Label lblEditorCdmVersion;
157
    private Text txtEditorCdmVersion;
158

    
159
    private final int MESSAGE_HEIGHT = 50;
160
    private final int COMBO_MIN_WIDTH =200;
161
    private final int CONTROLS_MIN_HEIGHT = 23; //does not seem to work yet
162
//  private final int MIN_EXP_HEIGHT = 380;
163

    
164
    private boolean autoConnect = false;
165
    private boolean loadLoginPrefs = true;
166
    private boolean isDevRemoteSource = false;
167

    
168
    private Job serverJob;
169
    protected Object result;
170

    
171
    private final Map<String, CdmServerInfo> serverInfoMap = new HashMap<>();
172

    
173
    private String serverName;
174
    private String instanceName;
175
    private CdmServerInfo selectedServerInfo;
176
    private CdmInstanceInfo selectedCdmInstance;
177
    private String login;
178
    private String password;
179

    
180
    /**
181
     * Create the dialog.
182
     * @param parent
183
     * @param style
184
     */
185
    public RemotingLoginDialog(Shell parent, int style) {
186
        super(parent, style);
187
        setText(Messages.RemotingLoginDialog_LABEL_LOGIN);
188
    }
189

    
190
    public Object open(ICdmRemoteSource source, boolean loadLoginPrefs, boolean autoConnect) {
191
        this.loadLoginPrefs = loadLoginPrefs;
192
        this.serverName = source.getName();
193
        if (source instanceof CdmRemoteLocalhostSource){
194
            this.instanceName = ((CdmRemoteLocalhostSource)source).getDatasourceName();
195
        }else{
196
            String contextPath = source.getContext();
197
            this.instanceName = contextPath == null? "" : contextPath.substring(contextPath.lastIndexOf("/") + 1); //$NON-NLS-1$
198
        }
199
        return open(serverName, instanceName, loadLoginPrefs, autoConnect);
200
    }
201

    
202
    public Object open(String serverName, String instanceName, boolean loadLoginPrefs, boolean autoConnect) {
203
        this.serverName = serverName;
204
        this.instanceName = instanceName;
205
        this.loadLoginPrefs = loadLoginPrefs;
206
        this.autoConnect = autoConnect;
207
        return open();
208
    }
209

    
210
    /**
211
     * Open the dialog.
212
     * @return the dialog result
213
     */
214
    public Object open() {
215

    
216
        createContents();
217
        if(serverName == null && instanceName == null) {
218
            readPrefLastServerInstance();
219
        }
220
        expandableCompositeAdvanced.setExpanded(false);
221

    
222
        setEditorInfo();
223
        populateCdmServerCombo();
224
        shlConnect.pack(true);
225

    
226
        setCenterPoint();
227
        shlConnect.open();
228

    
229
        Display display = getParent().getDisplay();
230
        while (!shlConnect.isDisposed()) {
231
            if (!display.isDisposed()){
232
                if (!display.readAndDispatch()) {
233
                    display.sleep();
234
                }
235
            }
236
        }
237
        return result;
238
    }
239

    
240
    /**
241
     * Create contents of the dialog.
242
     */
243
    private void createContents() {
244
        shlConnect = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE | SWT.CENTER);
245
        shlConnect.setText(LABEL_CONNECT);
246
        shlConnect.setLayout(new FillLayout(SWT.HORIZONTAL));
247

    
248
        remotingComposite = new Composite(shlConnect, SWT.NONE);
249
        remotingComposite.setLayout(new GridLayout(1, false));
250

    
251
        //server
252
        Composite cdmServerComposite = new Composite(remotingComposite, SWT.NONE);
253
        GridData gd_cdmServerComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
254
        cdmServerComposite.setLayoutData(gd_cdmServerComposite);
255
        cdmServerComposite.setLayout(new GridLayout(4, false));
256

    
257
        Label lblCdmServer = new Label(cdmServerComposite, SWT.NONE);
258
        lblCdmServer.setText(Messages.RemotingLoginDialog_LABEL_CDM_SERVER);
259
        lblCdmServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
260

    
261
        comboCdmServer = new Combo(cdmServerComposite, SWT.READ_ONLY);
262
        comboCdmServer.addSelectionListener(new SelectionAdapter() {
263
            @Override
264
            public void widgetSelected(SelectionEvent e) {
265
                onRefreshCdmServer();
266
            }
267
        });
268

    
269
        GridData gd_comboCdmServer = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
270

    
271
        comboCdmServer.setLayoutData(gd_comboCdmServer);
272
        comboCdmServer.select(0);
273

    
274
        txtCdmServerStatus = new Text(cdmServerComposite, SWT.BORDER);
275
        txtCdmServerStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
276
        txtCdmServerStatus.setEditable(false);
277
        GridData gd_txtCdmServerStatus = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
278
        gd_txtCdmServerStatus.minimumHeight = CONTROLS_MIN_HEIGHT;
279
        txtCdmServerStatus.setLayoutData(gd_txtCdmServerStatus);
280

    
281
        btnCdmServerRefresh = new Button(cdmServerComposite, SWT.NONE);
282
        btnCdmServerRefresh.addSelectionListener(new SelectionAdapter() {
283
            @Override
284
            public void widgetSelected(SelectionEvent e) {
285
                onRefreshCdmServer();
286
            }
287
        });
288
        GridData gd_btnCdmServerRefresh = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
289
        gd_btnCdmServerRefresh.minimumHeight = CONTROLS_MIN_HEIGHT;
290
        btnCdmServerRefresh.setLayoutData(gd_btnCdmServerRefresh);
291
        btnCdmServerRefresh.setText(Messages.RemotingLoginDialog_LABEL_REFRESH);
292

    
293
        //instance
294
        Label lblCdmInstance = new Label(cdmServerComposite, SWT.NONE);
295
        GridData gd_lblCdmInstance = new GridData(SWT.RIGHT, SWT.CENTER, false, true, 1, 1);
296
        //gd_lblCdmInstance.heightHint = 30;
297
        lblCdmInstance.setLayoutData(gd_lblCdmInstance);
298
        lblCdmInstance.setText(Messages.RemotingLoginDialog_LABEL_CDM_INSTANCE);
299

    
300
        comboCdmInstance = new Combo(cdmServerComposite, SWT.READ_ONLY);
301
        comboCdmInstance.addSelectionListener(new SelectionAdapter() {
302
            @Override
303
            public void widgetSelected(SelectionEvent e) {
304
                onRefreshCdmInstance();
305
            }
306
        });
307

    
308
        GridData gd_comboCdmInstance = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
309
        gd_comboCdmInstance.minimumWidth = COMBO_MIN_WIDTH;
310

    
311
        comboCdmInstance.setLayoutData(gd_comboCdmInstance);
312
        comboCdmInstance.select(0);
313

    
314
        txtCdmInstanceStatus = new Text(cdmServerComposite, SWT.BORDER);
315
        txtCdmInstanceStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
316
        txtCdmInstanceStatus.setEditable(false);
317
        GridData gd_txtCdmInstanceStatus = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
318
        gd_txtCdmInstanceStatus.minimumHeight = CONTROLS_MIN_HEIGHT;
319
        txtCdmInstanceStatus.setLayoutData(gd_txtCdmInstanceStatus);
320

    
321
        btnCdmInstanceRefresh = new Button(cdmServerComposite, SWT.FLAT);
322
        btnCdmInstanceRefresh.addSelectionListener(new SelectionAdapter() {
323
            @Override
324
            public void widgetSelected(SelectionEvent e) {
325
                onRefreshCdmInstance();
326
            }
327
        });
328
        GridData gd_btnCdmInstanceRefresh = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
329
        gd_btnCdmInstanceRefresh.minimumHeight = CONTROLS_MIN_HEIGHT;
330
        btnCdmInstanceRefresh.setLayoutData(gd_btnCdmInstanceRefresh);
331
        btnCdmInstanceRefresh.setText(Messages.RemotingLoginDialog_LABEL_REFRESH);
332

    
333
        //login + connect
334
        loginComposite = new Composite(remotingComposite, SWT.NONE);
335
        GridData gd_loginComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
336
        loginComposite.setLayoutData(gd_loginComposite);
337
        GridLayout gl_loginComposite = new GridLayout(6, false);
338
        gl_loginComposite.marginTop = 5;
339
        loginComposite.setLayout(gl_loginComposite);
340

    
341
        lblLogin = new Label(loginComposite, SWT.CENTER);
342
        GridData gd_lblLogin = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
343
        lblLogin.setLayoutData(gd_lblLogin);
344
        lblLogin.setText(Messages.RemotingLoginDialog_LABEL_LOGIN_COLON);
345

    
346
        txtLogin = new Text(loginComposite, SWT.BORDER);
347
        GridData gd_txtLogin = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
348
        gd_txtLogin.minimumWidth = 80;
349
        txtLogin.setLayoutData(gd_txtLogin);
350

    
351
        lblPassword = new Label(loginComposite, SWT.CENTER);
352
        lblPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
353
        lblPassword.setText(Messages.RemotingLoginDialog_LABEL_PASSWORD);
354

    
355
        txtPassword = new Text(loginComposite, SWT.BORDER | SWT.PASSWORD);
356
        GridData gd_txtPassword = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
357
        gd_txtPassword.minimumWidth = 80;
358
        txtPassword.setLayoutData(gd_txtPassword);
359
        @SuppressWarnings("unused")
360
        Label nope = new Label(loginComposite, SWT.NONE);
361
        txtPassword.addKeyListener(new KeyAdapter() {
362
        	@Override
363
        	public void keyPressed(KeyEvent e) {
364
        		if(e.character==SWT.CR){
365
        		    if(btnConnect.getText().equals(LABEL_CONNECT)){
366
                        onConnectButtonPressed();
367
                    }
368
        		}
369
        	}
370
        });
371

    
372
        btnConnect = new Button(loginComposite, SWT.FLAT);
373
        btnConnect.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
374
        btnConnect.addSelectionListener(new SelectionAdapter() {
375
			@Override
376
			public void widgetSelected(SelectionEvent e) {
377
				onConnectButtonPressed();
378
			}
379
		});
380
        btnConnect.setText(LABEL_CONNECT);
381

    
382
        //rememberMe + default values
383
        btnRememberMe = new Button(loginComposite, SWT.CHECK);
384
        btnRememberMe.setSelection(true);
385
        GridData gd_btnRememberMe = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1);
386
        btnRememberMe.setLayoutData(gd_btnRememberMe);
387
        btnRememberMe.setText(Messages.RemotingLoginDialog_LABEL_REMEMBER_ME);
388

    
389
        lblDefaultLogin = new Label(loginComposite, SWT.NONE);
390
        GridDataFactory.fillDefaults().span(4, 1).align(SWT.TRAIL, SWT.CENTER).applyTo(lblDefaultLogin);
391
        lblDefaultLogin.setText(String.format(Messages.RemotingLoginDialog_DEFAULT_LOGIN, DEFAULT_USER, DEFAULT_PASS));
392
        lblDefaultLogin.setVisible(false);
393

    
394
        styledTxtMessage = new StyledText(remotingComposite, SWT.NONE);
395
        styledTxtMessage.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
396
        styledTxtMessage.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
397
        styledTxtMessage.setSelectionBackground(SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION_TEXT));
398
        styledTxtMessage.setSelectionForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
399
        styledTxtMessage.setDoubleClickEnabled(false);
400
        styledTxtMessage.setEditable(false);
401
        styledTxtMessage.setWordWrap(true);
402

    
403
        GridData gd_styledTxtMessage = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
404
        gd_styledTxtMessage.exclude = true;
405
        gd_styledTxtMessage.minimumHeight = MESSAGE_HEIGHT;
406

    
407
        styledTxtMessage.setLayoutData(gd_styledTxtMessage);
408

    
409
        //Advanced
410
        expandableCompositeAdvanced = new ExpandableComposite(remotingComposite, SWT.NONE, ExpandableComposite.TWISTIE);
411
        GridData gd_xpndblcmpstAdvanced = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1);
412
        expandableCompositeAdvanced.setLayoutData(gd_xpndblcmpstAdvanced);
413
        expandableCompositeAdvanced.addExpansionListener(new IExpansionListener() {
414
            @Override
415
            public void expansionStateChanged(ExpansionEvent e) {
416
                shlConnect.pack(true);
417
            }
418
            @Override
419
            public void expansionStateChanging(ExpansionEvent e) {
420
            }
421
        });
422
        expandableCompositeAdvanced.setText(Messages.RemotingLoginDialog_LABEL_ADVANCED);
423
        expandableCompositeAdvanced.setExpanded(true);
424

    
425
        compAdvanced = new Composite(expandableCompositeAdvanced, SWT.NONE);
426
        expandableCompositeAdvanced.setClient(compAdvanced);
427
        compAdvanced.setLayout(new GridLayout(4, false));
428

    
429
        lblPort = new Label(compAdvanced, SWT.CENTER);
430
        lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
431
        lblPort.setText(Messages.RemotingLoginDialog_LABEL_PORT);
432

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

    
438
        lblServerCdmlibVersion = new Label(compAdvanced, SWT.CENTER);
439
        lblServerCdmlibVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
440
        lblServerCdmlibVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDMLIB_VERSION);
441

    
442
        txtServerCdmlibVersion = new Text(compAdvanced, SWT.BORDER);
443
        txtServerCdmlibVersion.setEditable(false);
444
        txtServerCdmlibVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
445

    
446
//        btnStopServer = new Button(compAdvanced, SWT.FLAT);
447
//        btnStopServer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
448
//        btnStopServer.addMouseListener(new MouseAdapter() {
449
//            @Override
450
//            public void mouseUp(MouseEvent e) {
451
//                onStopManagedServer();
452
//            }
453
//        });
454
//        btnStopServer.setText(Messages.RemotingLoginDialog_LABEL_STOP_MANAGED_SERVER);
455

    
456
        lblEditorCdmlibVersion = new Label(compAdvanced, SWT.CENTER);
457
        lblEditorCdmlibVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
458
        lblEditorCdmlibVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDMLIB_VERSION);
459

    
460
        txtEditorCdmlibVersion = new Text(compAdvanced, SWT.BORDER);
461
        txtEditorCdmlibVersion.setEditable(false);
462
        txtEditorCdmlibVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
463
        addEmptyCells(2);
464

    
465
        lblServerSchemaVersion = new Label(compAdvanced, SWT.CENTER);
466
        lblServerSchemaVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
467
        lblServerSchemaVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDM_VERSION);
468

    
469
        txtServerSchemaVersion = new Text(compAdvanced, SWT.BORDER);
470
        txtServerSchemaVersion.setEditable(false);
471
        txtServerSchemaVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
472
        addEmptyCells(2);
473

    
474
        lblEditorCdmVersion = new Label(compAdvanced, SWT.CENTER);
475
        lblEditorCdmVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
476
        lblEditorCdmVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDM_VERSION);
477

    
478
        txtEditorCdmVersion = new Text(compAdvanced, SWT.BORDER);
479
        txtEditorCdmVersion.setEditable(false);
480
        txtEditorCdmVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
481
    }
482

    
483
    public void setCenterPoint() {
484
        Rectangle parentSize = getParent().getBounds();
485
        Rectangle shellSize = shlConnect.getBounds();
486
        int locationX = (parentSize.width - shellSize.width)/2+parentSize.x;
487
        int locationY = (parentSize.height - shellSize.height)/2+parentSize.y;
488
        shlConnect.setLocation(new Point(locationX, locationY));
489

    
490
    }
491

    
492

    
493

    
494

    
495

    
496

    
497
    @SuppressWarnings("unused")
498
    private void addEmptyCells(int cnt) {
499
        for (int i = 0; i < cnt; i++) {
500
            new Label(compAdvanced, SWT.NONE);
501
        }
502
    }
503

    
504
	private void onConnectButtonPressed() {
505
//		if(selectedServerInfo.isLocalhostMgd() && !isSelectedCdmInstanceRunningInManagedServer()) {
506
//			startManagedServer();
507
//		} else {
508
			connect();
509
			if (CdmStore.isActive() && CdmStore.currentAuthentiationHasOneOfRoles(Role.ROLE_REMOTING)){
510
			    PreferencesUtil.setNomenclaturalCodePreferences();
511
			}
512
//		}
513
	}
514

    
515
    private void populateCdmServerCombo() {
516
        Job job = new Job(Messages.RemotingLoginDialog_RETRIEVE_SERVER_INSTANCES) {
517
            @Override
518
            protected IStatus run(IProgressMonitor monitor) {
519
                Display.getDefault().syncExec(new Runnable() {
520
                    @Override
521
                    public void run() {
522
                        //TODO performance
523
                        for(CdmServerInfo csii : CdmServerInfo.getCdmServers()) {
524
                            serverInfoMap.put(csii.getName(), csii);
525
                            comboCdmServer.add(csii.getName());
526
                        }
527
                        int serverIndex = -1;
528
                        if(serverName != null) {
529
                            serverIndex = comboCdmServer.indexOf(serverName);
530
                        }
531
                        if(serverIndex == -1) {
532
                            comboCdmServer.select(0);
533
                            autoConnect = false;
534
                        } else {
535
                            comboCdmServer.select(serverIndex);
536
                        }
537
                        ICdmSource devRemoteSource = CdmServerInfo.getDevServerRemoteSource();
538
                        if(devRemoteSource != null) {
539
                            isDevRemoteSource = true;
540
                            String username = System.getProperty("cdm.server.dev.username"); //$NON-NLS-1$
541
                            String password = System.getProperty("cdm.server.dev.password"); //$NON-NLS-1$
542
                            if(username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
543
                                txtLogin.setText(username);
544
                                txtPassword.setText(password);
545
                                CdmStoreRemote.connect(devRemoteSource, RemotingLoginDialog.this);
546
                            }
547
                        } else {
548
                            onRefreshCdmServer();
549
                        }
550
                    }
551
                });
552
                return Status.OK_STATUS;
553
            }
554
        };
555
        job.schedule();
556
    }
557

    
558
    private void onRefreshCdmServer() {
559
        try{
560
            txtCdmServerStatus.setText(STATUS_CHECKING_AVAILABILITY);
561
            clearOnServerChange();
562
            emptyCredentials();
563
            updateSelectedCdmServer();
564
            Display.getDefault().asyncExec(new Runnable() {
565
                @Override
566
                public void run() {
567
                    checkSelectedCdmServer();
568
                }
569
            });
570
        }
571
        catch(SWTException e){
572
            //catch widget is disposed exception which may occur if
573
            //dialog is closed but the runnable tries to update
574
        }
575
    }
576

    
577
    private void updateSelectedCdmServer() {
578
        int selIndex = comboCdmServer.getSelectionIndex();
579
        if(selIndex != -1) {
580
            selectedServerInfo = serverInfoMap.get(comboCdmServer.getItem(selIndex));
581
        }
582
    }
583

    
584
    private void updatePort() {
585
        txtPort.setText(""); //$NON-NLS-1$
586
        if(selectedServerInfo != null) {
587
            int port = selectedServerInfo.getPort();
588
            if(port == CdmServerInfo.NULL_PORT) {
589
                txtPort.setText(CdmServerInfo.NULL_PORT_STRING);
590
            } else {
591
                txtPort.setText(String.valueOf(port));
592
            }
593
        }
594
    }
595

    
596
    private int getPort() {
597
        int port = CdmServerInfo.NULL_PORT;
598
        try {
599
            port = Integer.valueOf(txtPort.getText());
600
        } catch (NumberFormatException nfe) {
601
            if(!CdmServerInfo.NULL_PORT_STRING.equals(txtPort.getText())) {
602
                setMessage(Messages.RemotingLoginDialog_MESSAGE_PORT_SHOULD_BE_INTEGER);
603
            }
604
        }
605
        return port;
606
    }
607

    
608
    private void checkSelectedCdmServer() {
609
        try{
610
            if(selectedServerInfo != null) {
611
                if(selectedServerInfo.isLocalhost()) {
612
                    txtPort.setEditable(true);
613
                    txtPort.setEnabled(true);
614
                }
615
                try {
616
                    if(selectedServerInfo.pingServer()) {
617
                        txtCdmServerStatus.setText(STATUS_AVAILABLE);
618
                        populateCdmInstanceCombo(true);
619
                        if(selectedServerInfo.isLocalhost()){
620
                            setCdmlibVersion(txtServerCdmlibVersion);
621
                        }else{
622
                            String serverVersionTimestamp = generateLastModifiedTooltip(selectedServerInfo.getCdmlibLastModified());
623
                            txtServerCdmlibVersion.setText(selectedServerInfo.getCdmlibServicesVersion() + ":" + serverVersionTimestamp); //$NON-NLS-1$
624
                        }
625
                    } else {
626
                        txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
627
                        comboCdmInstance.removeAll();
628
                        disableCdmInstanceControls("", ""); //$NON-NLS-1$ //$NON-NLS-2$
629
                    }
630
                } catch (CdmServerException | IOException e) {
631
                    txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
632
                    // TODO distinguish java.net.ConnectException: Connection refused, java.net.SocketTimeoutException: Read timed out
633
                    Throwable cause = e;
634
                    if(e instanceof CdmServerException && e.getCause() != null){
635
                        cause = e.getCause();
636
                    }
637
                    String message = Messages.RemotingLoginDialog_CONNECTION_FAILED_MESSAGE;
638
                    if(cause instanceof SocketTimeoutException){
639
                        message = Messages.RemotingLoginDialog_CONNECTION_TIMEOUT_MESSAGE;
640
                    }
641
                    MessagingUtils.warningDialog(Messages.RemotingLoginDialog_CONNECTION_FAILED_TITLE, this,
642
                            message);
643
                    logger.warn(Messages.RemotingLoginDialog_CONNECTION_FAILED_TITLE, e);
644
                }
645
            }
646
            updatePort();
647
        }
648
        catch(SWTException e){
649
            //catch widget is disposed exception which may occur if
650
            //dialog is closed but the runnable tries to update
651
        }
652
    }
653

    
654
    private void populateCdmInstanceCombo(final boolean forceRefresh) {
655
        comboCdmInstance.removeAll();
656
        comboCdmInstance.setEnabled(false);
657
        btnConnect.setEnabled(false);
658
        txtCdmInstanceStatus.setText(STATUS_RETRIEVING);
659
        txtCdmInstanceStatus.setToolTipText(""); //$NON-NLS-1$
660

    
661
        serverJob = new Job(Messages.RemotingLoginDialog_RETRIEVE_SERVER_INSTANCES) {
662
            @Override
663
            protected IStatus run(IProgressMonitor monitor) {
664
                try {
665
                    if(selectedServerInfo != null) {
666
                        if(forceRefresh) {
667
                            selectedServerInfo.refreshInstances();
668
                        }
669
                        final List<CdmInstanceInfo> instances = selectedServerInfo.getInstances();
670
                        Display.getDefault().asyncExec(new Runnable() {
671
                            @Override
672
                            public void run() {
673
                                if(!instances.isEmpty()) {
674
                                    for(CdmInstanceInfo cdmInstance : instances) {
675
                                        comboCdmInstance.add(cdmInstance.getName());
676
                                    }
677
                                    int instanceIndex = -1;
678
                                    if(instanceName != null) {
679
                                        instanceIndex = comboCdmInstance.indexOf(instanceName);
680
                                    }
681
                                    if(instanceIndex == -1) {
682
                                        comboCdmInstance.select(0);
683
                                        autoConnect = false;
684
                                    } else {
685
                                        comboCdmInstance.select(instanceIndex);
686
                                    }
687
                                    onRefreshCdmInstance();
688
                                    comboCdmInstance.setEnabled(true);
689
                                    if(autoConnect) {
690
                                        connect();
691
                                    }
692
                                } else {
693
                                    txtCdmInstanceStatus.setText(STATUS_NO_INSTANCES);
694
                                    btnConnect.setEnabled(false);
695
                                }
696
                            }
697
                        });
698
                    }
699
                } catch (final CdmServerException e) {
700
                    MessagingUtils.warn(getClass(), e);
701
                    Display.getDefault().asyncExec(new Runnable() {
702
                        @Override
703
                        public void run() {
704
                            disableCdmInstanceControls(STATUS_NOT_AVAILABLE, e.getMessage());
705
                        }
706
                    });
707
                }
708
                return Status.OK_STATUS;
709
            }
710
        };
711

    
712
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE) && !isDevRemoteSource) {
713
            // Start the Job
714
            serverJob.schedule();
715
        }
716
    }
717

    
718
    private void disableCdmInstanceControls(String cdmInstanceStatus, String tooltip) {
719
        txtCdmInstanceStatus.setText(cdmInstanceStatus);
720
        txtCdmInstanceStatus.setToolTipText(tooltip);
721
        comboCdmInstance.setEnabled(false);
722
        btnConnect.setEnabled(false);
723
    }
724

    
725
    private void onRefreshCdmInstance() {
726
        txtCdmInstanceStatus.setText(STATUS_CHECKING_AVAILABILITY);
727
        clearOnInstanceChange();
728
        updateSelectedCdmInstance();
729
        checkSelectedCdmInstance();
730
//        updateManagedServerControls();
731
    }
732

    
733
    private void updateSelectedCdmInstance() {
734
        int selIndex = comboCdmInstance.getSelectionIndex();
735
        if(selIndex != -1) {
736
            selectedCdmInstance = selectedServerInfo.getInstanceFromName(comboCdmInstance.getItem(selIndex));
737
            if(loadLoginPrefs) {
738
                readPrefCredentials();
739
            }
740
        }
741
    }
742

    
743
//    private void updateManagedServerControls() {
744
//        if(selectedServerInfo.isLocalhostMgd()) {
745
//            if(isSelectedCdmInstanceRunningInManagedServer()) {
746
//                txtCdmInstanceStatus.setText(STATUS_STARTED);
747
//            } else {
748
//                txtCdmInstanceStatus.setText(STATUS_NOT_STARTED);
749
//            }
750
//            btnConnect.setEnabled(true);
751
//            selectedServerInfo.setPort(getManagedServerPort());
752
//            updatePort();
753
//        }
754
//
755
//        if(isManagedServerRunning()) {
756
//            btnStopServer.setEnabled(true);
757
//        } else {
758
//            btnStopServer.setEnabled(false);
759
//        }
760
//    }
761

    
762
//    private boolean isManagedServerRunning() {
763
//        return CdmStore.getManagedServer() != null && CdmStore.getManagedServer().isAlive();
764
//    }
765
//
766
//    private boolean isSelectedCdmInstanceRunningInManagedServer() {
767
//        return CdmStore.getManagedServer() != null &&
768
//                CdmStore.getManagedServer().isAlive() &&
769
//                selectedServerInfo.isLocalhostMgd() &&
770
//                CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName());
771
//    }
772
//
773
//    private void startManagedServer() {
774
//        if(isManagedServerRunning()) {
775
//            if(CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())) {
776
//                return;
777
//            } else {
778
//                Display.getDefault().syncExec(new Runnable() {
779
//                    @Override
780
//                    public void run() {
781
//                        onStopManagedServer();
782
//                    }
783
//                });
784
//            }
785
//        }
786
//
787
//        boolean forceSchemaCreate = !schemaExists(selectedCdmInstance);
788
//        boolean forceSchemaUpdate = LABEL_UPDATE_SCHEMA_VERSION.equals(btnConnect.getText());
789
//
790
//        Job job = new Job(Messages.RemotingLoginDialog_JOB_SERVER_LAUNCH) {
791
//
792
//            @Override
793
//            public IStatus run(IProgressMonitor monitor) {
794
//                String mgdServerConfigFileName = "mgd.datasources.xml"; //$NON-NLS-1$
795
//                String config = CdmServerUtils.convertEditorToServerConfig();
796
//                int maxUnits = 50;
797
//                monitor.beginTask(Messages.RemotingLoginDialog_TASK_LAUNCHING_SERVER, maxUnits);
798
//                try {
799
//                    monitor.subTask(String.format(Messages.RemotingLoginDialog_GENERATING_CONFIG_FILE, selectedCdmInstance.getName()));
800
//                    File managedServerConfigFile = CdmServerUtils.writeManagedServerConfig(config, mgdServerConfigFileName);
801
//                    monitor.worked(1);
802
//
803
//                    Class ref = Class.forName("CdmServer");
804
//                    ICdmServer cdmServer = (ICdmServer)ref.newInstance();
805
//                    cdmServer.setDataSourceParams(selectedCdmInstance.getName(), managedServerConfigFile);
806
////                    ICdmServer cdmServer = new CdmServer(selectedCdmInstance.getName(), managedServerConfigFile);
807
//                    cdmServer.setForceSchemaCreate(forceSchemaCreate);
808
//                    cdmServer.setForceSchemaUpdate(forceSchemaUpdate);
809
//                    CdmStore.setManagedServer(cdmServer);
810
//                    monitor.subTask(Messages.RemotingLoginDialog_STARTING_MGD_SERVER);
811
//                    cdmServer.start(false, RemotingLoginDialog.this);
812
//                    int serverUnits = 0;
813
//
814
//                    // the following loop is a 'fake' progress monitoring where the progress
815
//                    // bar is advanced by one unit every second until maxUnits -2
816
//                    while(!CdmStore.getManagedServer().isStarted() && !CdmStore.getManagedServer().isFailed()) {
817
//                        if(serverUnits < maxUnits - 2) {
818
//                            try {
819
//                                Thread.sleep(1000);
820
//                            } catch (InterruptedException e) {
821
//                            }
822
//                            monitor.worked(1);
823
//                            serverUnits++;
824
//                        }
825
//                    }
826
//                    Display.getDefault().syncExec(()->{
827
//                                hide(false);
828
//                                updateManagedServerControls();
829
//                                connect();
830
//                    });
831
//                } catch (IOException ioe) {
832
//                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_GENERATING_CONFIG_FILE,
833
//                            this,
834
//                            ioe.getMessage(),
835
//                            TaxeditorStorePlugin.PLUGIN_ID,
836
//                            ioe,
837
//                            true);
838
//                } catch (CdmEmbeddedServerException cese) {
839
//                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STARTING_SERVER,
840
//                            this,
841
//                            cese.getMessage(),
842
//                            TaxeditorStorePlugin.PLUGIN_ID,
843
//                            cese,
844
//                            true);
845
//                } catch (ClassNotFoundException e1) {
846
//                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STARTING_SERVER,
847
//                            this,
848
//                            e1.getMessage(),
849
//                            TaxeditorStorePlugin.PLUGIN_ID,
850
//                            e1,
851
//                            true);
852
//                } catch (InstantiationException e1) {
853
//                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STARTING_SERVER,
854
//                            this,
855
//                            e1.getMessage(),
856
//                            TaxeditorStorePlugin.PLUGIN_ID,
857
//                            e1,
858
//                            true);
859
//                } catch (IllegalAccessException e1) {
860
//                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STARTING_SERVER,
861
//                            this,
862
//                            e1.getMessage(),
863
//                            TaxeditorStorePlugin.PLUGIN_ID,
864
//                            e1,
865
//                            true);
866
//                } finally {
867
//                    monitor.done();
868
//                }
869
//                // NOTE: Errors thrown during server startup are passed to the handleError() implementation
870
//                // TODO: is the above catch clause for CdmEmbeddedServerException still valuable?
871
//
872
//                return Status.OK_STATUS;
873
//            }
874
//       };
875
//
876
//        // configure the job
877
//        job.setProperty(IProgressConstants.KEEP_PROPERTY, true);
878
//        job.setUser(true);
879
//        // schedule job
880
//        hide(true);
881
//        job.schedule();
882
//    }
883

    
884
    private boolean schemaExists(CdmInstanceInfo instanceInfo) {
885
        if (instanceInfo.getDataSource() != null){
886
            try {
887
                //TODO we need a new method in cdmlib to check for existing schema
888
                String schemaVersion = instanceInfo.getDataSource().getDbSchemaVersion();
889
                return schemaVersion != null;
890
            } catch (CdmSourceException e) {
891
                return false;
892
            }
893
        }else{
894
            return true;
895
        }
896
    }
897

    
898
    private String managedSchemaVersion(CdmInstanceInfo instanceInfo) throws CdmSourceException{
899
        if (instanceInfo.getDataSource() != null){
900
            return instanceInfo.getDataSource().getDbSchemaVersion();
901
        }else{
902
            throw new RuntimeException("ManagedSchemaVersion only available for managed server instances.");
903
        }
904
    }
905
    private int compareSchemaVersion(CdmInstanceInfo instanceInfo) throws CdmSourceException {
906
        return CdmMetaData.compareVersion(managedSchemaVersion(instanceInfo), CdmMetaData.getDbSchemaVersion(), 3, null);
907
    }
908

    
909
    @Override
910
    public void handleError(final Throwable t) {
911

    
912
        Display.getDefault().syncExec(()-> {
913
            serverJob.cancel();
914

    
915
            String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
916
            String  message = t.getMessage();
917

    
918
            MessagingUtils.errorDialog(title,
919
                    this,
920
                    message,
921
                    TaxeditorStorePlugin.PLUGIN_ID,
922
                    t,
923
                    true);
924
        });
925
    }
926

    
927
//    private void onStopManagedServer() {
928
//        try {
929
//            CdmStore.getManagedServer().stop();
930
//        } catch (Exception e) {
931
//            MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STOPPING_SERVER,
932
//                    this,
933
//                    String.format(Messages.RemotingLoginDialog_COULD_NOT_STOP_SERVER, CdmStore.getManagedServer().getPort()),
934
//                    TaxeditorStorePlugin.PLUGIN_ID,
935
//                    e,
936
//                    true);
937
//        }
938
//        CdmStore.setManagedServer(null);
939
//        updateManagedServerControls();
940
//    }
941

    
942
//    private int getManagedServerPort() {
943
//        return CdmStore.getManagedServer() == null ? CdmServerInfo.NULL_PORT : CdmStore.getManagedServer().getPort();
944
//    }
945

    
946
    private void checkSelectedCdmInstance() {
947

    
948
//        if (selectedServerInfo.isLocalhostMgd()){
949
//            checkManagedSelectedInstance();
950
//        }else
951
            if (txtCdmServerStatus.getText().equals(STATUS_AVAILABLE)) {
952

    
953
            boolean available = false;
954
            String instanceStatus = STATUS_NOT_AVAILABLE;
955
            String message = null;
956
            try {
957
                if(selectedServerInfo.pingInstance(selectedCdmInstance, getPort())) {
958
                    instanceStatus = STATUS_AVAILABLE;
959
                    available = true;
960
                } else {
961
                    instanceStatus = STATUS_NOT_AVAILABLE;
962
                    available = false;
963
                }
964

    
965
                if(available) {
966
                    txtServerSchemaVersion.setText(selectedServerInfo.getCdmRemoteSource(selectedCdmInstance, getPort()).getDbSchemaVersion());
967

    
968
                    int compareDbSchemaVersion = selectedServerInfo.compareDbSchemaVersion(selectedCdmInstance, getPort());
969

    
970
                    int compareCdmlibServicesVersion = 0;
971
                    boolean disableServicesApiTimestampCheck =
972
                            PreferencesUtil.getBooleanValue((IPreferenceKeys.DISABLE_SERVICES_API_TIMESTAMP_CHECK));
973
                    if(!disableServicesApiTimestampCheck) {
974
                        compareCdmlibServicesVersion = selectedServerInfo.compareCdmlibServicesVersion();
975
                    }
976

    
977
                    if(compareDbSchemaVersion > 0 || compareCdmlibServicesVersion > 0) {
978
                        instanceStatus = STATUS_NOT_COMPATIBLE;
979
                        available = false;
980
                        message = MESG_COMPATIBLE_EDITOR_OLD;
981
                    } else if(compareDbSchemaVersion < 0 || compareCdmlibServicesVersion < 0) {
982
                        instanceStatus = STATUS_NOT_COMPATIBLE;
983
                        available = false;
984
                        message = MESG_COMPATIBLE_SERVER_OLD;
985
                    } else {
986
                        instanceStatus =  STATUS_AVAILABLE;
987
                        available = true;
988
                        message = ""; //$NON-NLS-1$
989
                    }
990
                }
991
            } catch (Exception e) {
992
                txtCdmInstanceStatus.setToolTipText(e.getMessage());
993
            } finally {
994
                lblDefaultLogin.setVisible(false);
995
                btnConnect.setEnabled(available);
996
                txtCdmInstanceStatus.setText(instanceStatus);
997
                if(!StringUtils.isBlank(message)) {
998
                    setMessage(message);
999
                }
1000
            }
1001
        }
1002
    }
1003

    
1004
//    private void checkManagedSelectedInstance() {
1005
//        boolean available = false;
1006
//        String instanceStatus = STATUS_NOT_AVAILABLE;
1007
//        String message = null;
1008
//        String connect = LABEL_CONNECT;
1009
//        Integer color = null;
1010
//        String schemaVersion = CdmMetaData.getDbSchemaVersion();
1011
//
1012
//        if (!schemaExists(selectedCdmInstance)){
1013
//            message = MESG_SCHEMA_MISSING;
1014
//            connect = LABEL_CREATE_SCHEMA;
1015
//            color = BTN_COLOR_ATTENTION;
1016
//            schemaVersion = MESG_NO_SCHEMA;
1017
//        } else {
1018
//            int compare;
1019
//            try {
1020
//                schemaVersion = managedSchemaVersion(selectedCdmInstance);
1021
//                compare = compareSchemaVersion(selectedCdmInstance);
1022
//                if (compare > 0){
1023
//                    instanceStatus = STATUS_NOT_COMPATIBLE;
1024
//                    message = MESG_COMPATIBLE_EDITOR_OLD;
1025
//                    available = false;
1026
//                }else if (compare < 0){
1027
//                    instanceStatus = STATUS_NOT_COMPATIBLE;
1028
//                    message = MESG_UPDATE_SCHEMA_VERSION;
1029
//                    available = true;
1030
//                    connect = LABEL_UPDATE_SCHEMA_VERSION;
1031
//                    color = BTN_COLOR_ATTENTION;
1032
//                }else{
1033
//                    available = true;
1034
//                    instanceStatus = STATUS_AVAILABLE;
1035
//                }
1036
//            } catch (CdmSourceException e) {
1037
//                available = false;
1038
//            }
1039
//        }
1040
//
1041
//        setManagedValues(available, instanceStatus, connect, color, schemaVersion);
1042
//        setMessage(message);
1043
//    }
1044

    
1045
//    private void setManagedValues(boolean available, String instanceStatus, String connect, Integer color,
1046
//            String schemaVersion) {
1047
//        Display.getDefault().syncExec(()->{
1048
//            btnConnect.setEnabled(available);
1049
//            btnConnect.setText(connect);
1050
//            Color systemColor = null;
1051
//            if(color != null) {
1052
//                systemColor = Display.getCurrent().getSystemColor(color);
1053
//            }
1054
//            btnConnect.setBackground(systemColor);
1055
//            btnConnect.requestLayout();
1056
//            txtCdmInstanceStatus.setText(instanceStatus);
1057
//            txtServerSchemaVersion.setText(schemaVersion);
1058
//            lblDefaultLogin.setVisible(true);
1059
//         });
1060
//    }
1061

    
1062
    private void connect() {
1063
        checkSelectedCdmInstance();
1064

    
1065
        if(!txtCdmInstanceStatus.getText().equals(STATUS_AVAILABLE)) {
1066
            return;
1067
        }
1068

    
1069
        ICdmRemoteSource source = selectedServerInfo.getCdmRemoteSource(selectedCdmInstance, getPort());
1070

    
1071
        if(!validateLogin(source)) {
1072
            return;
1073
        }
1074

    
1075
        try {
1076
            CdmStoreRemote.connect(source, this);
1077
        } catch (Exception e) {
1078
            // Do not expect anything to go wrong at this point, so we throw a runtime exception
1079
            // if any problems
1080
            throw new RuntimeException(e);
1081
        }
1082
    }
1083

    
1084
    public boolean isRememberMe() {
1085
        return btnRememberMe.getSelection();
1086
    }
1087

    
1088
    private void persistPrefLastServerInstance() {
1089
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1090
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
1091

    
1092
        lastServerInstancePrefs.put(LAST_SERVER_KEY, selectedServerInfo.getName());
1093
        lastServerInstancePrefs.put(LAST_INSTANCE_KEY, selectedCdmInstance.getName());
1094

    
1095
        flushPreferences(lastServerInstancePrefs);
1096
    }
1097

    
1098
    private void persistPrefCredentials() {
1099
         IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1100
         Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1101
         credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
1102
         credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
1103
         flushPreferences(credentialsPrefs);
1104
    }
1105

    
1106
    private void removePrefCredentials() {
1107
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1108
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1109
        credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
1110
        credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
1111
        removePreferences(credentialsPrefs);
1112
    }
1113

    
1114
    private void removePreferences(Preferences prefs) {
1115
        try {
1116
            prefs.removeNode();
1117
        } catch (BackingStoreException bse) {
1118
            setMessage(bse.getMessage());
1119
        }
1120
    }
1121

    
1122
    private void flushPreferences(Preferences prefs) {
1123
        try {
1124
            prefs.flush();
1125
        } catch (BackingStoreException bse) {
1126
            setMessage(bse.getMessage());
1127
        }
1128
    }
1129

    
1130
    private void readPrefCredentials() {
1131
        String username, password;
1132
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1133
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1134
        username = credentialsPrefs.get(getUsernamePrefKey(), ""); //$NON-NLS-1$
1135
        txtLogin.setText(username);
1136
        password = credentialsPrefs.get(getPasswordPrefKey(),""); //$NON-NLS-1$
1137
        txtPassword.setText(password);
1138
        if(username.isEmpty() || password.isEmpty()) {
1139
            autoConnect = false;
1140
        }
1141
    }
1142

    
1143
    private void readPrefLastServerInstance() {
1144
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1145
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
1146

    
1147
        serverName = lastServerInstancePrefs.get(LAST_SERVER_KEY, null);
1148
        instanceName = lastServerInstancePrefs.get(LAST_INSTANCE_KEY, null);
1149
    }
1150

    
1151
    private void emptyCredentials() {
1152
        txtLogin.setText(""); //$NON-NLS-1$
1153
        txtPassword.setText(""); //$NON-NLS-1$
1154
    }
1155

    
1156
    private String getUsernamePrefKey() {
1157
        return selectedServerInfo.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + USERNAME_SUFFIX;
1158
    }
1159

    
1160
    private String getPasswordPrefKey() {
1161
        return selectedServerInfo.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + PASSWORD_SUFFIX;
1162
    }
1163

    
1164
    private boolean validateLogin(ICdmRemoteSource remoteSource) {
1165
        if(getUsername() == null || getUsername().isEmpty()) {
1166
            setMessage(Messages.RemotingLoginDialog_LOGIN_CANNOT_BE_EMPTY);
1167
            return false;
1168
        }
1169
        if(getPassword() == null || getPassword().isEmpty()) {
1170
            setMessage(Messages.RemotingLoginDialog_PASSWORD_CANNOT_BE_EMPTY);
1171
            return false;
1172
        }
1173

    
1174
        try {
1175
            IUserService userService = CdmApplicationRemoteConfiguration.getUserService(remoteSource);
1176
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(getUsername(), getPassword());
1177
            CdmApplicationRemoteConfiguration.getAuthenticationManager(userService).authenticate(token);
1178
        } catch(BadCredentialsException e){
1179
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1180
            return false;
1181
        } catch(LockedException e){
1182
            setMessage(LoginManager.ACCOUNT_LOCKED_MESSAGE);
1183
            return false;
1184
        } catch(IllegalArgumentException e){
1185
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1186
            return false;
1187
        }
1188
        return true;
1189
    }
1190

    
1191
    @Override
1192
    public String getUsername() {
1193
        return txtLogin.getText();
1194
    }
1195

    
1196
    @Override
1197
    public String getPassword() {
1198
        return txtPassword.getText();
1199
    }
1200

    
1201
    @Override
1202
    public void setMessage(String message) {
1203
        if(CdmUtils.isNotBlank(message)) {
1204
//            if(message.length() > 50) {
1205
//                styledTxtMessage.setToolTipText(message);
1206
//                message = message.substring(0,50) + "..."; //$NON-NLS-1$
1207
//            }
1208
            styledTxtMessage.setText(message);
1209
            styledTxtMessage.setVisible(true);
1210
            ((GridData)styledTxtMessage.getLayoutData()).exclude = false;
1211
//            shlConnect.setMinimumSize(MIN_WIDTH, getHeightWithoutMessage() + MESSAGE_HEIGHT);
1212
            shlConnect.pack(true);
1213
        } else {
1214
            if (!styledTxtMessage.isDisposed()){
1215
                styledTxtMessage.setText(""); //$NON-NLS-1$
1216
                styledTxtMessage.setVisible(false);
1217
                ((GridData)styledTxtMessage.getLayoutData()).exclude = true;
1218
            }
1219
            if(!shlConnect.isDisposed()){
1220
                shlConnect.pack(true);
1221
            }
1222
        }
1223
        if (!remotingComposite.isDisposed()){
1224
            remotingComposite.layout();
1225
        }
1226
    }
1227

    
1228
//    private int getHeightWithoutMessage() {
1229
//        if(xpndblcmpstAdvanced.isExpanded()) {
1230
//            return MIN_EXP_HEIGHT;
1231
//        } else {
1232
//            return MIN_HEIGHT;
1233
//        }
1234
//    }
1235

    
1236
    @Override
1237
    public void hide(boolean isHidden) {
1238
        if (!shlConnect.isDisposed()){
1239
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1240
                shlConnect.setVisible(!isHidden);
1241
            }
1242
        }
1243
    }
1244

    
1245
    public void dispose() {
1246
        if (!shlConnect.isDisposed()){
1247
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1248
                shlConnect.dispose();
1249
            }
1250
        }
1251
    }
1252

    
1253
    @Override
1254
    public void onComplete() {
1255
        Display.getDefault().asyncExec(new Runnable() {
1256
            @Override
1257
            public void run() {
1258
                if(selectedCdmInstance!=null){
1259
                    if(isRememberMe()) {
1260
                        persistPrefCredentials();
1261
                    }else{
1262
                        removePrefCredentials();
1263
                    }
1264
                    persistPrefLastServerInstance();
1265
                }
1266
                dispose();
1267
            }
1268
        });
1269
    }
1270

    
1271
    private String generateLastModifiedTooltip(String cdmlibLastModified) {
1272
        if(StringUtils.isBlank(cdmlibLastModified)) {
1273
            return ""; //$NON-NLS-1$
1274
        }
1275
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.z"); //$NON-NLS-1$
1276
        Date cdmlibLastModifiedDate;
1277
        String cdmlibLastModifiedTimestamp = ""; //$NON-NLS-1$
1278

    
1279
        cdmlibLastModifiedDate = new Date(Long.valueOf(cdmlibLastModified));
1280
        cdmlibLastModifiedTimestamp = sdf.format(cdmlibLastModifiedDate);
1281

    
1282
        return cdmlibLastModifiedTimestamp;
1283
    }
1284

    
1285
    private void setEditorInfo() {
1286
        txtEditorCdmVersion.setText(CdmMetaData.getDbSchemaVersion());
1287
        setCdmlibVersion(txtEditorCdmlibVersion);
1288
    }
1289

    
1290
    private void setCdmlibVersion(Text txt) {
1291
        String editorVersionTimestamp = generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified());
1292
        txt.setText(CdmApplicationState.getCdmlibVersion() + ":" + editorVersionTimestamp); //$NON-NLS-1$
1293
    }
1294

    
1295
    private void clearOnServerChange() {
1296
        setMessage(""); //$NON-NLS-1$
1297
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1298
        txtServerCdmlibVersion.setText(""); //$NON-NLS-1$
1299
        txtServerCdmlibVersion.setToolTipText(""); //$NON-NLS-1$
1300
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1301
        comboCdmInstance.removeAll();
1302
        txtCdmInstanceStatus.setText(""); //$NON-NLS-1$
1303
        txtPort.setEditable(false);
1304
        txtPort.setEnabled(false);
1305
    }
1306

    
1307
    private void clearOnInstanceChange() {
1308
        setMessage(""); //$NON-NLS-1$
1309
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1310
        btnConnect.setText(LABEL_CONNECT);
1311
        btnConnect.setBackground(null);
1312
        btnConnect.requestLayout();
1313
    }
1314

    
1315
    @SuppressWarnings("unused")  //in work, for future centralized handling of control's status
1316
    private void updateControls(){
1317

    
1318
        //server
1319
//      comboCdmServer; //nothing to change
1320
        String strServerStatus = this.selectedServerInfo != null? STATUS_NOT_AVAILABLE : STATUS_AVAILABLE;
1321
        txtCdmServerStatus.setText(strServerStatus);
1322
//      btnCdmServerRefresh;  //nothing to change
1323

    
1324
        //database
1325
//        comboCdmInstance
1326
        String strInstanceStatus = this.selectedCdmInstance != null? STATUS_NOT_AVAILABLE : STATUS_AVAILABLE;
1327
        txtCdmInstanceStatus.setText(strInstanceStatus);
1328
//        btnCdmInstanceRefresh;  //nothing to change
1329

    
1330
        //login + connect
1331
        txtLogin.setText(Nz(login));
1332
        txtPassword.setText(Nz(password));
1333
        btnConnect.setText(LABEL_CONNECT);  //TODO
1334
        btnConnect.setEnabled(true);
1335

    
1336
        //rememberMe + defaultValues
1337
//        btnRememberMe;
1338
//        lblDefaultLogin;
1339

    
1340
        //message
1341
//        styledTxtMessage;
1342

    
1343
        //Advanced
1344
//        txtPort
1345
//        btnStopServer;
1346

    
1347
//        txtServerCdmlibVersion;
1348
//        txtEditorCdmlibVersion;
1349
//        txtServerSchemaVersion;
1350
//        txtEditorCdmVersion;
1351
    }
1352

    
1353
    private String Nz(String value) {
1354
        return CdmUtils.Nz(value);
1355
    }
1356
}
    (1-1/1)