Project

General

Profile

Download (55 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.lang3.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.graphics.Color;
39
import org.eclipse.swt.graphics.Point;
40
import org.eclipse.swt.graphics.Rectangle;
41
import org.eclipse.swt.layout.FillLayout;
42
import org.eclipse.swt.layout.GridData;
43
import org.eclipse.swt.layout.GridLayout;
44
import org.eclipse.swt.widgets.Button;
45
import org.eclipse.swt.widgets.Combo;
46
import org.eclipse.swt.widgets.Composite;
47
import org.eclipse.swt.widgets.Dialog;
48
import org.eclipse.swt.widgets.Display;
49
import org.eclipse.swt.widgets.Label;
50
import org.eclipse.swt.widgets.Shell;
51
import org.eclipse.swt.widgets.Text;
52
import org.eclipse.ui.forms.events.ExpansionEvent;
53
import org.eclipse.ui.forms.events.IExpansionListener;
54
import org.eclipse.ui.forms.widgets.ExpandableComposite;
55
import org.eclipse.ui.progress.IProgressConstants;
56
import org.eclipse.wb.swt.SWTResourceManager;
57
import org.osgi.service.prefs.BackingStoreException;
58
import org.osgi.service.prefs.Preferences;
59
import org.springframework.security.authentication.BadCredentialsException;
60
import org.springframework.security.authentication.LockedException;
61
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
62

    
63
import eu.etaxonomy.cdm.api.application.CdmApplicationRemoteConfiguration;
64
import eu.etaxonomy.cdm.api.application.CdmApplicationState;
65
import eu.etaxonomy.cdm.api.service.IUserService;
66
import eu.etaxonomy.cdm.common.CdmUtils;
67
import eu.etaxonomy.cdm.config.CdmSourceException;
68
import eu.etaxonomy.cdm.config.ICdmSource;
69
import eu.etaxonomy.cdm.model.metadata.CdmMetaData;
70
import eu.etaxonomy.cdm.persistence.permission.Role;
71
import eu.etaxonomy.taxeditor.l10n.Messages;
72
import eu.etaxonomy.taxeditor.model.MessagingUtils;
73
import eu.etaxonomy.taxeditor.preference.IPreferenceKeys;
74
import eu.etaxonomy.taxeditor.preference.PreferencesUtil;
75
import eu.etaxonomy.taxeditor.remoting.server.CdmServerException;
76
import eu.etaxonomy.taxeditor.remoting.server.CdmServerUtils;
77
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteLocalhostSource;
78
import eu.etaxonomy.taxeditor.remoting.source.CdmServerInfo;
79
import eu.etaxonomy.taxeditor.remoting.source.CdmServerInfo.CdmInstanceInfo;
80
import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
81
import eu.etaxonomy.taxeditor.store.CdmStore;
82
import eu.etaxonomy.taxeditor.store.LoginManager;
83
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
84
import eu.etaxonomy.taxeditor.webapp.CdmEmbeddedServerException;
85
import eu.etaxonomy.taxeditor.webapp.CdmServer;
86
import eu.etaxonomy.taxeditor.webapp.ICDMServerError;
87

    
88
/**
89
 * @author cmathew
90
 * @date 20 Jan 2015
91
 */
92
public class RemotingLoginDialog extends Dialog implements ICDMServerError {
93

    
94
    private Logger logger = Logger.getLogger(getClass());
95

    
96
    private static final String DEFAULT_PASS = "00000"; //$NON-NLS-1$
97
    private static final String DEFAULT_USER = "admin"; //$NON-NLS-1$
98

    
99
    private final static String STATUS_AVAILABLE = Messages.RemotingLoginDialog_STATUS_AVAILABLE;
100
    private final static String STATUS_NOT_AVAILABLE = Messages.RemotingLoginDialog_STATUS_NOT_AVAILABLE;
101
    private final static String STATUS_STARTED = Messages.RemotingLoginDialog_STATUS_STARTED;
102
    private final static String STATUS_NOT_STARTED = Messages.RemotingLoginDialog_STATUS_NOT_STARTED;
103
    private final static String STATUS_RETRIEVING = Messages.RemotingLoginDialog_STATUS_RETRIEVING;
104
    private final static String STATUS_CHECKING_AVAILABILITY = Messages.RemotingLoginDialog_STATUS_CHECKING;
105
    private final static String STATUS_NO_INSTANCES = Messages.RemotingLoginDialog_STATUS_NO_INSTANCES_FOUND;
106
    private final static String STATUS_NOT_COMPATIBLE = Messages.RemotingLoginDialog_STATUS_NOT_COMPATIBLE;
107

    
108
    private final static String MESG_COMPATIBLE_EDITOR_OLD = Messages.RemotingLoginDialog_UPDATE_EDITOR;
109
    private final static String MESG_COMPATIBLE_SERVER_OLD = Messages.RemotingLoginDialog_CHOOSE_COMPATIBLE_CDM_SERVER;
110
    private final static String MESG_SCHEMA_MISSING = Messages.RemotingLoginDialog_SCHEMA_MISSING;
111
    private final static String MESG_NO_SCHEMA = Messages.RemotingLoginDialog_NO_SCHEMA;
112

    
113
    private final static String LABEL_CONNECT = Messages.RemotingLoginDialog_LABEL_CONNECT;
114
    private final static String LABEL_CREATE_SCHEMA = Messages.RemotingLoginDialog_LABEL_CREATE_SCHEMA;
115
    private final static String LABEL_UPDATE_SCHEMA_VERSION = Messages.RemotingLoginDialog_LABEL_UPDATE_SCHEMA_VERSION;
116
    private final static String MESG_UPDATE_SCHEMA_VERSION = Messages.RemotingLoginDialog_MSG_UPDATE_SCHEMA_VERSION;
117

    
118
    private static final int BTN_COLOR_ATTENTION = SWT.COLOR_RED;
119

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

    
122
    private final static String LOGIN_NODE = "login"; //$NON-NLS-1$
123
    private final static String USERNAME_SUFFIX = "_username"; //$NON-NLS-1$
124
    private final static String PASSWORD_SUFFIX = "_password"; //$NON-NLS-1$
125

    
126
    private final static String LAST_SERVER_INSTANCE_NODE = "lastServerInstance"; //$NON-NLS-1$
127
    private final static String LAST_SERVER_KEY = "lastServerKey"; //$NON-NLS-1$
128
    private final static String LAST_INSTANCE_KEY = "lastInstanceKey"; //$NON-NLS-1$
129

    
130
    protected Shell shlConnect;
131
    private Text txtCdmServerStatus;
132
    private Text txtCdmInstanceStatus;
133
    private Combo comboCdmServer;
134
    private Combo comboCdmInstance;
135
    private Button btnConnect;
136

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

    
156
    private Label lblEditorCdmlibVersion;
157
    private Text txtEditorCdmlibVersion;
158
    private Label lblServerSchemaVersion;
159
    private Text txtServerSchemaVersion;
160
    private Label lblEditorCdmVersion;
161
    private Text txtEditorCdmVersion;
162

    
163
    private final int MESSAGE_HEIGHT = 50;
164
    private final int COMBO_MIN_WIDTH =200;
165
    private final int CONTROLS_MIN_HEIGHT = 23; //does not seem to work yet
166
//  private final int MIN_EXP_HEIGHT = 380;
167

    
168
    private boolean autoConnect = false;
169
    private boolean loadLoginPrefs = true;
170
    private boolean isDevRemoteSource = false;
171

    
172
    private Job serverJob;
173
    protected Object result;
174

    
175
    private final Map<String, CdmServerInfo> serverInfoMap = new HashMap<>();
176

    
177
    private String serverName;
178
    private String instanceName;
179
    private CdmServerInfo selectedServerInfo;
180
    private CdmInstanceInfo selectedCdmInstance;
181
    private String login;
182
    private String password;
183

    
184
    /**
185
     * Create the dialog.
186
     * @param parent
187
     * @param style
188
     */
189
    public RemotingLoginDialog(Shell parent, int style) {
190
        super(parent, style);
191
        setText(Messages.RemotingLoginDialog_LABEL_LOGIN);
192
    }
193

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

    
206
    public Object open(String serverName, String instanceName, boolean loadLoginPrefs, boolean autoConnect) {
207
        this.serverName = serverName;
208
        this.instanceName = instanceName;
209
        this.loadLoginPrefs = loadLoginPrefs;
210
        this.autoConnect = autoConnect;
211
        return open();
212
    }
213

    
214
    /**
215
     * Open the dialog.
216
     * @return the dialog result
217
     */
218
    public Object open() {
219

    
220
        createContents();
221
        if(serverName == null && instanceName == null) {
222
            readPrefLastServerInstance();
223
        }
224
        expandableCompositeAdvanced.setExpanded(false);
225

    
226
        setEditorInfo();
227
        populateCdmServerCombo();
228
        shlConnect.pack(true);
229

    
230
        setCenterPoint();
231
        shlConnect.open();
232

    
233
        Display display = getParent().getDisplay();
234
        while (!shlConnect.isDisposed()) {
235
            if (!display.isDisposed()){
236
                if (!display.readAndDispatch()) {
237
                    display.sleep();
238
                }
239
            }
240
        }
241
        return result;
242
    }
243

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

    
252
        remotingComposite = new Composite(shlConnect, SWT.NONE);
253
        remotingComposite.setLayout(new GridLayout(1, false));
254

    
255
        //server
256
        Composite cdmServerComposite = new Composite(remotingComposite, SWT.NONE);
257
        GridData gd_cdmServerComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
258
        cdmServerComposite.setLayoutData(gd_cdmServerComposite);
259
        cdmServerComposite.setLayout(new GridLayout(4, false));
260

    
261
        Label lblCdmServer = new Label(cdmServerComposite, SWT.NONE);
262
        lblCdmServer.setText(Messages.RemotingLoginDialog_LABEL_CDM_SERVER);
263
        lblCdmServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
264

    
265
        comboCdmServer = new Combo(cdmServerComposite, SWT.READ_ONLY);
266
        comboCdmServer.addSelectionListener(new SelectionAdapter() {
267
            @Override
268
            public void widgetSelected(SelectionEvent e) {
269
                onRefreshCdmServer();
270
            }
271
        });
272

    
273
        GridData gd_comboCdmServer = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
274

    
275
        comboCdmServer.setLayoutData(gd_comboCdmServer);
276
        comboCdmServer.select(0);
277

    
278
        txtCdmServerStatus = new Text(cdmServerComposite, SWT.BORDER);
279
        txtCdmServerStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
280
        txtCdmServerStatus.setEditable(false);
281
        GridData gd_txtCdmServerStatus = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
282
        gd_txtCdmServerStatus.minimumHeight = CONTROLS_MIN_HEIGHT;
283
        txtCdmServerStatus.setLayoutData(gd_txtCdmServerStatus);
284

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

    
297
        //instance
298
        Label lblCdmInstance = new Label(cdmServerComposite, SWT.NONE);
299
        GridData gd_lblCdmInstance = new GridData(SWT.RIGHT, SWT.CENTER, false, true, 1, 1);
300
        //gd_lblCdmInstance.heightHint = 30;
301
        lblCdmInstance.setLayoutData(gd_lblCdmInstance);
302
        lblCdmInstance.setText(Messages.RemotingLoginDialog_LABEL_CDM_INSTANCE);
303

    
304
        comboCdmInstance = new Combo(cdmServerComposite, SWT.READ_ONLY);
305
        comboCdmInstance.addSelectionListener(new SelectionAdapter() {
306
            @Override
307
            public void widgetSelected(SelectionEvent e) {
308
                onRefreshCdmInstance();
309
            }
310
        });
311

    
312
        GridData gd_comboCdmInstance = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
313
        gd_comboCdmInstance.minimumWidth = COMBO_MIN_WIDTH;
314

    
315
        comboCdmInstance.setLayoutData(gd_comboCdmInstance);
316
        comboCdmInstance.select(0);
317

    
318
        txtCdmInstanceStatus = new Text(cdmServerComposite, SWT.BORDER);
319
        txtCdmInstanceStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
320
        txtCdmInstanceStatus.setEditable(false);
321
        GridData gd_txtCdmInstanceStatus = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
322
        gd_txtCdmInstanceStatus.minimumHeight = CONTROLS_MIN_HEIGHT;
323
        txtCdmInstanceStatus.setLayoutData(gd_txtCdmInstanceStatus);
324

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

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

    
345
        lblLogin = new Label(loginComposite, SWT.CENTER);
346
        GridData gd_lblLogin = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
347
        lblLogin.setLayoutData(gd_lblLogin);
348
        lblLogin.setText(Messages.RemotingLoginDialog_LABEL_LOGIN_COLON);
349

    
350
        txtLogin = new Text(loginComposite, SWT.BORDER);
351
        GridData gd_txtLogin = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
352
        gd_txtLogin.minimumWidth = 80;
353
        txtLogin.setLayoutData(gd_txtLogin);
354

    
355
        lblPassword = new Label(loginComposite, SWT.CENTER);
356
        lblPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
357
        lblPassword.setText(Messages.RemotingLoginDialog_LABEL_PASSWORD);
358

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

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

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

    
393
        lblDefaultLogin = new Label(loginComposite, SWT.NONE);
394
        GridDataFactory.fillDefaults().span(4, 1).align(SWT.TRAIL, SWT.CENTER).applyTo(lblDefaultLogin);
395
        lblDefaultLogin.setText(String.format(Messages.RemotingLoginDialog_DEFAULT_LOGIN, DEFAULT_USER, DEFAULT_PASS));
396
        lblDefaultLogin.setVisible(false);
397

    
398
        styledTxtMessage = new StyledText(remotingComposite, SWT.NONE);
399
        styledTxtMessage.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
400
        styledTxtMessage.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
401
        styledTxtMessage.setSelectionBackground(SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION_TEXT));
402
        styledTxtMessage.setSelectionForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
403
        styledTxtMessage.setDoubleClickEnabled(false);
404
        styledTxtMessage.setEditable(false);
405
        styledTxtMessage.setWordWrap(true);
406

    
407
        GridData gd_styledTxtMessage = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
408
        gd_styledTxtMessage.exclude = true;
409
        gd_styledTxtMessage.minimumHeight = MESSAGE_HEIGHT;
410

    
411
        styledTxtMessage.setLayoutData(gd_styledTxtMessage);
412

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

    
429
        compAdvanced = new Composite(expandableCompositeAdvanced, SWT.NONE);
430
        expandableCompositeAdvanced.setClient(compAdvanced);
431
        compAdvanced.setLayout(new GridLayout(4, false));
432

    
433
        lblPort = new Label(compAdvanced, SWT.CENTER);
434
        lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
435
        lblPort.setText(Messages.RemotingLoginDialog_LABEL_PORT);
436

    
437
        txtPort = new Text(compAdvanced, SWT.BORDER);
438
        GridData gd_txtPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
439
        gd_txtPort.minimumWidth = 50;
440
        txtPort.setLayoutData(gd_txtPort);
441

    
442
        lblServerCdmlibVersion = new Label(compAdvanced, SWT.CENTER);
443
        lblServerCdmlibVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
444
        lblServerCdmlibVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDMLIB_VERSION);
445

    
446
        txtServerCdmlibVersion = new Text(compAdvanced, SWT.BORDER);
447
        txtServerCdmlibVersion.setEditable(false);
448
        txtServerCdmlibVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
449

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

    
460
        lblEditorCdmlibVersion = new Label(compAdvanced, SWT.CENTER);
461
        lblEditorCdmlibVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
462
        lblEditorCdmlibVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDMLIB_VERSION);
463

    
464
        txtEditorCdmlibVersion = new Text(compAdvanced, SWT.BORDER);
465
        txtEditorCdmlibVersion.setEditable(false);
466
        txtEditorCdmlibVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
467
        addEmptyCells(2);
468

    
469
        lblServerSchemaVersion = new Label(compAdvanced, SWT.CENTER);
470
        lblServerSchemaVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
471
        lblServerSchemaVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDM_VERSION);
472

    
473
        txtServerSchemaVersion = new Text(compAdvanced, SWT.BORDER);
474
        txtServerSchemaVersion.setEditable(false);
475
        txtServerSchemaVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
476
        addEmptyCells(2);
477

    
478
        lblEditorCdmVersion = new Label(compAdvanced, SWT.CENTER);
479
        lblEditorCdmVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
480
        lblEditorCdmVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDM_VERSION);
481

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

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

    
494
    }
495

    
496

    
497

    
498

    
499

    
500

    
501
    @SuppressWarnings("unused")
502
    private void addEmptyCells(int cnt) {
503
        for (int i = 0; i < cnt; i++) {
504
            new Label(compAdvanced, SWT.NONE);
505
        }
506
    }
507

    
508
	private void onConnectButtonPressed() {
509
		if(selectedServerInfo.isLocalhostMgd() && !isSelectedCdmInstanceRunningInManagedServer()) {
510
			startManagedServer();
511
		} else {
512
			connect();
513
			if (CdmStore.isActive() && CdmStore.currentAuthentiationHasOneOfRoles(Role.ROLE_REMOTING)){
514
			    PreferencesUtil.setNomenclaturalCodePreferences();
515
			}
516
		}
517
	}
518

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

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

    
581
    private void updateSelectedCdmServer() {
582
        int selIndex = comboCdmServer.getSelectionIndex();
583
        if(selIndex != -1) {
584
            selectedServerInfo = serverInfoMap.get(comboCdmServer.getItem(selIndex));
585
        }
586
    }
587

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

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

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

    
658
    private void populateCdmInstanceCombo(final boolean forceRefresh) {
659
        comboCdmInstance.removeAll();
660
        comboCdmInstance.setEnabled(false);
661
        btnConnect.setEnabled(false);
662
        txtCdmInstanceStatus.setText(STATUS_RETRIEVING);
663
        txtCdmInstanceStatus.setToolTipText(""); //$NON-NLS-1$
664

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

    
716
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE) && !isDevRemoteSource) {
717
            // Start the Job
718
            serverJob.schedule();
719
        }
720
    }
721

    
722
    private void disableCdmInstanceControls(String cdmInstanceStatus, String tooltip) {
723
        txtCdmInstanceStatus.setText(cdmInstanceStatus);
724
        txtCdmInstanceStatus.setToolTipText(tooltip);
725
        comboCdmInstance.setEnabled(false);
726
        btnConnect.setEnabled(false);
727
    }
728

    
729
    private void onRefreshCdmInstance() {
730
        txtCdmInstanceStatus.setText(STATUS_CHECKING_AVAILABILITY);
731
        clearOnInstanceChange();
732
        updateSelectedCdmInstance();
733
        checkSelectedCdmInstance();
734
        updateManagedServerControls();
735
    }
736

    
737
    private void updateSelectedCdmInstance() {
738
        int selIndex = comboCdmInstance.getSelectionIndex();
739
        if(selIndex != -1) {
740
            selectedCdmInstance = selectedServerInfo.getInstanceFromName(comboCdmInstance.getItem(selIndex));
741
            if(loadLoginPrefs) {
742
                readPrefCredentials();
743
            }
744
        }
745
    }
746

    
747
    private void updateManagedServerControls() {
748
        if(selectedServerInfo.isLocalhostMgd()) {
749
            if(isSelectedCdmInstanceRunningInManagedServer()) {
750
                txtCdmInstanceStatus.setText(STATUS_STARTED);
751
            } else {
752
                txtCdmInstanceStatus.setText(STATUS_NOT_STARTED);
753
            }
754
            btnConnect.setEnabled(true);
755
            selectedServerInfo.setPort(getManagedServerPort());
756
            updatePort();
757
        }
758

    
759
        if(isManagedServerRunning()) {
760
            btnStopServer.setEnabled(true);
761
        } else {
762
            btnStopServer.setEnabled(false);
763
        }
764
    }
765

    
766
    private boolean isManagedServerRunning() {
767
        return CdmStore.getManagedServer() != null && CdmStore.getManagedServer().isAlive();
768
    }
769

    
770
    private boolean isSelectedCdmInstanceRunningInManagedServer() {
771
        return CdmStore.getManagedServer() != null &&
772
                CdmStore.getManagedServer().isAlive() &&
773
                selectedServerInfo.isLocalhostMgd() &&
774
                CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName());
775
    }
776

    
777
    private void startManagedServer() {
778
        if(isManagedServerRunning()) {
779
            if(CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())) {
780
                return;
781
            } else {
782
                Display.getDefault().syncExec(new Runnable() {
783
                    @Override
784
                    public void run() {
785
                        onStopManagedServer();
786
                    }
787
                });
788
            }
789
        }
790

    
791
        boolean forceSchemaCreate = !schemaExists(selectedCdmInstance);
792
        boolean forceSchemaUpdate = LABEL_UPDATE_SCHEMA_VERSION.equals(btnConnect.getText());
793

    
794
        Job job = new Job(Messages.RemotingLoginDialog_JOB_SERVER_LAUNCH) {
795

    
796
            @Override
797
            public IStatus run(IProgressMonitor monitor) {
798
                String mgdServerConfigFileName = "mgd.datasources.xml"; //$NON-NLS-1$
799
                String config = CdmServerUtils.convertEditorToServerConfig();
800
                int maxUnits = 50;
801
                monitor.beginTask(Messages.RemotingLoginDialog_TASK_LAUNCHING_SERVER, maxUnits);
802
                try {
803
                    monitor.subTask(String.format(Messages.RemotingLoginDialog_GENERATING_CONFIG_FILE, selectedCdmInstance.getName()));
804
                    File managedServerConfigFile = CdmServerUtils.writeManagedServerConfig(config, mgdServerConfigFileName);
805
                    monitor.worked(1);
806
                    CdmServer 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
                } finally {
846
                    monitor.done();
847
                }
848
                // NOTE: Errors thrown during server startup are passed to the handleError() implementation
849
                // TODO: is the above catch clause for CdmEmbeddedServerException still valuable?
850

    
851
                return Status.OK_STATUS;
852
            }
853
       };
854

    
855
        // configure the job
856
        job.setProperty(IProgressConstants.KEEP_PROPERTY, true);
857
        job.setUser(true);
858
        // schedule job
859
        hide(true);
860
        job.schedule();
861
    }
862

    
863
    private boolean schemaExists(CdmInstanceInfo instanceInfo) {
864
        if (instanceInfo.getDataSource() != null){
865
            try {
866
                //TODO we need a new method in cdmlib to check for existing schema
867
                String schemaVersion = instanceInfo.getDataSource().getDbSchemaVersion();
868
                return schemaVersion != null;
869
            } catch (CdmSourceException e) {
870
                return false;
871
            }
872
        }else{
873
            return true;
874
        }
875
    }
876

    
877
    private String managedSchemaVersion(CdmInstanceInfo instanceInfo) throws CdmSourceException{
878
        if (instanceInfo.getDataSource() != null){
879
            return instanceInfo.getDataSource().getDbSchemaVersion();
880
        }else{
881
            throw new RuntimeException("ManagedSchemaVersion only available for managed server instances.");
882
        }
883
    }
884
    private int compareSchemaVersion(CdmInstanceInfo instanceInfo) throws CdmSourceException {
885
        return CdmMetaData.compareVersion(managedSchemaVersion(instanceInfo), CdmMetaData.getDbSchemaVersion(), 3, null);
886
    }
887

    
888
    @Override
889
    public void handleError(final Throwable t) {
890

    
891
        Display.getDefault().syncExec(()-> {
892
            serverJob.cancel();
893

    
894
            String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
895
            String  message = t.getMessage();
896

    
897
            MessagingUtils.errorDialog(title,
898
                    this,
899
                    message,
900
                    TaxeditorStorePlugin.PLUGIN_ID,
901
                    t,
902
                    true);
903
        });
904
    }
905

    
906
    private void onStopManagedServer() {
907
        try {
908
            CdmStore.getManagedServer().stop();
909
        } catch (Exception e) {
910
            MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STOPPING_SERVER,
911
                    this,
912
                    String.format(Messages.RemotingLoginDialog_COULD_NOT_STOP_SERVER, CdmStore.getManagedServer().getPort()),
913
                    TaxeditorStorePlugin.PLUGIN_ID,
914
                    e,
915
                    true);
916
        }
917
        CdmStore.setManagedServer(null);
918
        updateManagedServerControls();
919
    }
920

    
921
    private int getManagedServerPort() {
922
        return CdmStore.getManagedServer() == null ? CdmServerInfo.NULL_PORT : CdmStore.getManagedServer().getPort();
923
    }
924

    
925
    private void checkSelectedCdmInstance() {
926

    
927
        if (selectedServerInfo.isLocalhostMgd()){
928
            checkManagedSelectedInstance();
929
        }else if (txtCdmServerStatus.getText().equals(STATUS_AVAILABLE)) {
930

    
931
            boolean available = false;
932
            String instanceStatus = STATUS_NOT_AVAILABLE;
933
            String message = null;
934
            try {
935
                if(selectedServerInfo.pingInstance(selectedCdmInstance, getPort())) {
936
                    instanceStatus = STATUS_AVAILABLE;
937
                    available = true;
938
                } else {
939
                    instanceStatus = STATUS_NOT_AVAILABLE;
940
                    available = false;
941
                }
942

    
943
                if(available) {
944
                    txtServerSchemaVersion.setText(selectedServerInfo.getCdmRemoteSource(selectedCdmInstance, getPort()).getDbSchemaVersion());
945

    
946
                    int compareDbSchemaVersion = selectedServerInfo.compareDbSchemaVersion(selectedCdmInstance, getPort());
947

    
948
                    int compareCdmlibServicesVersion = 0;
949
                    boolean disableServicesApiTimestampCheck =
950
                            PreferencesUtil.getBooleanValue((IPreferenceKeys.DISABLE_SERVICES_API_TIMESTAMP_CHECK));
951
                    if(!disableServicesApiTimestampCheck) {
952
                        compareCdmlibServicesVersion = selectedServerInfo.compareCdmlibServicesVersion();
953
                    }
954

    
955
                    if(compareDbSchemaVersion > 0 || compareCdmlibServicesVersion > 0) {
956
                        instanceStatus = STATUS_NOT_COMPATIBLE;
957
                        available = false;
958
                        message = MESG_COMPATIBLE_EDITOR_OLD;
959
                    } else if(compareDbSchemaVersion < 0 || compareCdmlibServicesVersion < 0) {
960
                        instanceStatus = STATUS_NOT_COMPATIBLE;
961
                        available = false;
962
                        message = MESG_COMPATIBLE_SERVER_OLD;
963
                    } else {
964
                        instanceStatus =  STATUS_AVAILABLE;
965
                        available = true;
966
                        message = ""; //$NON-NLS-1$
967
                    }
968
                }
969
            } catch (Exception e) {
970
                txtCdmInstanceStatus.setToolTipText(e.getMessage());
971
            } finally {
972
                lblDefaultLogin.setVisible(false);
973
                btnConnect.setEnabled(available);
974
                txtCdmInstanceStatus.setText(instanceStatus);
975
                if(!StringUtils.isBlank(message)) {
976
                    setMessage(message);
977
                }
978
            }
979
        }
980
    }
981

    
982
    private void checkManagedSelectedInstance() {
983
        boolean available = false;
984
        String instanceStatus = STATUS_NOT_AVAILABLE;
985
        String message = null;
986
        String connect = LABEL_CONNECT;
987
        Integer color = null;
988
        String schemaVersion = CdmMetaData.getDbSchemaVersion();
989

    
990
        if (!schemaExists(selectedCdmInstance)){
991
            message = MESG_SCHEMA_MISSING;
992
            connect = LABEL_CREATE_SCHEMA;
993
            color = BTN_COLOR_ATTENTION;
994
            schemaVersion = MESG_NO_SCHEMA;
995
        } else {
996
            int compare;
997
            try {
998
                schemaVersion = managedSchemaVersion(selectedCdmInstance);
999
                compare = compareSchemaVersion(selectedCdmInstance);
1000
                if (compare > 0){
1001
                    instanceStatus = STATUS_NOT_COMPATIBLE;
1002
                    message = MESG_COMPATIBLE_EDITOR_OLD;
1003
                    available = false;
1004
                }else if (compare < 0){
1005
                    instanceStatus = STATUS_NOT_COMPATIBLE;
1006
                    message = MESG_UPDATE_SCHEMA_VERSION;
1007
                    available = true;
1008
                    connect = LABEL_UPDATE_SCHEMA_VERSION;
1009
                    color = BTN_COLOR_ATTENTION;
1010
                }else{
1011
                    available = true;
1012
                    instanceStatus = STATUS_AVAILABLE;
1013
                }
1014
            } catch (CdmSourceException e) {
1015
                available = false;
1016
            }
1017
        }
1018

    
1019
        setManagedValues(available, instanceStatus, connect, color, schemaVersion);
1020
        setMessage(message);
1021
    }
1022

    
1023
    private void setManagedValues(boolean available, String instanceStatus, String connect, Integer color,
1024
            String schemaVersion) {
1025
        Display.getDefault().syncExec(()->{
1026
            btnConnect.setEnabled(available);
1027
            btnConnect.setText(connect);
1028
            Color systemColor = null;
1029
            if(color != null) {
1030
                systemColor = Display.getCurrent().getSystemColor(color);
1031
            }
1032
            btnConnect.setBackground(systemColor);
1033
            btnConnect.requestLayout();
1034
            txtCdmInstanceStatus.setText(instanceStatus);
1035
            txtServerSchemaVersion.setText(schemaVersion);
1036
            lblDefaultLogin.setVisible(true);
1037
         });
1038
    }
1039

    
1040
    private void connect() {
1041
        checkSelectedCdmInstance();
1042

    
1043
        if(!txtCdmInstanceStatus.getText().equals(STATUS_AVAILABLE)) {
1044
            return;
1045
        }
1046

    
1047
        ICdmRemoteSource source = selectedServerInfo.getCdmRemoteSource(selectedCdmInstance, getPort());
1048

    
1049
        if(!validateLogin(source)) {
1050
            return;
1051
        }
1052

    
1053
        try {
1054
            CdmStore.connect(source, this);
1055
        } catch (Exception e) {
1056
            // Do not expect anything to go wrong at this point, so we throw a runtime exception
1057
            // if any problems
1058
            throw new RuntimeException(e);
1059
        }
1060
    }
1061

    
1062
    public boolean isRememberMe() {
1063
        return btnRememberMe.getSelection();
1064
    }
1065

    
1066
    private void persistPrefLastServerInstance() {
1067
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1068
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
1069

    
1070
        lastServerInstancePrefs.put(LAST_SERVER_KEY, selectedServerInfo.getName());
1071
        lastServerInstancePrefs.put(LAST_INSTANCE_KEY, selectedCdmInstance.getName());
1072

    
1073
        flushPreferences(lastServerInstancePrefs);
1074
    }
1075

    
1076
    private void persistPrefCredentials() {
1077
         IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1078
         Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1079
         credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
1080
         credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
1081
         flushPreferences(credentialsPrefs);
1082
    }
1083

    
1084
    private void removePrefCredentials() {
1085
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1086
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1087
        credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
1088
        credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
1089
        removePreferences(credentialsPrefs);
1090
    }
1091

    
1092
    private void removePreferences(Preferences prefs) {
1093
        try {
1094
            prefs.removeNode();
1095
        } catch (BackingStoreException bse) {
1096
            setMessage(bse.getMessage());
1097
        }
1098
    }
1099

    
1100
    private void flushPreferences(Preferences prefs) {
1101
        try {
1102
            prefs.flush();
1103
        } catch (BackingStoreException bse) {
1104
            setMessage(bse.getMessage());
1105
        }
1106
    }
1107

    
1108
    private void readPrefCredentials() {
1109
        String username, password;
1110
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1111
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1112
        username = credentialsPrefs.get(getUsernamePrefKey(), ""); //$NON-NLS-1$
1113
        txtLogin.setText(username);
1114
        password = credentialsPrefs.get(getPasswordPrefKey(),""); //$NON-NLS-1$
1115
        txtPassword.setText(password);
1116
        if(username.isEmpty() || password.isEmpty()) {
1117
            autoConnect = false;
1118
        }
1119
    }
1120

    
1121
    private void readPrefLastServerInstance() {
1122
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1123
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
1124

    
1125
        serverName = lastServerInstancePrefs.get(LAST_SERVER_KEY, null);
1126
        instanceName = lastServerInstancePrefs.get(LAST_INSTANCE_KEY, null);
1127
    }
1128

    
1129
    private void emptyCredentials() {
1130
        txtLogin.setText(""); //$NON-NLS-1$
1131
        txtPassword.setText(""); //$NON-NLS-1$
1132
    }
1133

    
1134
    private String getUsernamePrefKey() {
1135
        return selectedServerInfo.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + USERNAME_SUFFIX;
1136
    }
1137

    
1138
    private String getPasswordPrefKey() {
1139
        return selectedServerInfo.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + PASSWORD_SUFFIX;
1140
    }
1141

    
1142
    private boolean validateLogin(ICdmRemoteSource remoteSource) {
1143
        if(getUsername() == null || getUsername().isEmpty()) {
1144
            setMessage(Messages.RemotingLoginDialog_LOGIN_CANNOT_BE_EMPTY);
1145
            return false;
1146
        }
1147
        if(getPassword() == null || getPassword().isEmpty()) {
1148
            setMessage(Messages.RemotingLoginDialog_PASSWORD_CANNOT_BE_EMPTY);
1149
            return false;
1150
        }
1151

    
1152
        try {
1153
            IUserService userService = CdmApplicationRemoteConfiguration.getUserService(remoteSource);
1154
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(getUsername(), getPassword());
1155
            CdmApplicationRemoteConfiguration.getAuthenticationManager(userService).authenticate(token);
1156
        } catch(BadCredentialsException e){
1157
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1158
            return false;
1159
        } catch(LockedException e){
1160
            setMessage(LoginManager.ACCOUNT_LOCKED_MESSAGE);
1161
            return false;
1162
        } catch(IllegalArgumentException e){
1163
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1164
            return false;
1165
        }
1166
        return true;
1167
    }
1168

    
1169
    public String getUsername() {
1170
        return txtLogin.getText();
1171
    }
1172

    
1173
    public String getPassword() {
1174
        return txtPassword.getText();
1175
    }
1176

    
1177
    public void setMessage(String message) {
1178
        if(CdmUtils.isNotBlank(message)) {
1179
//            if(message.length() > 50) {
1180
//                styledTxtMessage.setToolTipText(message);
1181
//                message = message.substring(0,50) + "..."; //$NON-NLS-1$
1182
//            }
1183
            styledTxtMessage.setText(message);
1184
            styledTxtMessage.setVisible(true);
1185
            ((GridData)styledTxtMessage.getLayoutData()).exclude = false;
1186
//            shlConnect.setMinimumSize(MIN_WIDTH, getHeightWithoutMessage() + MESSAGE_HEIGHT);
1187
            shlConnect.pack(true);
1188
        } else {
1189
            if (!styledTxtMessage.isDisposed()){
1190
                styledTxtMessage.setText(""); //$NON-NLS-1$
1191
                styledTxtMessage.setVisible(false);
1192
                ((GridData)styledTxtMessage.getLayoutData()).exclude = true;
1193
            }
1194
            if(!shlConnect.isDisposed()){
1195
                shlConnect.pack(true);
1196
            }
1197
        }
1198
        if (!remotingComposite.isDisposed()){
1199
            remotingComposite.layout();
1200
        }
1201
    }
1202

    
1203
//    private int getHeightWithoutMessage() {
1204
//        if(xpndblcmpstAdvanced.isExpanded()) {
1205
//            return MIN_EXP_HEIGHT;
1206
//        } else {
1207
//            return MIN_HEIGHT;
1208
//        }
1209
//    }
1210

    
1211
    public void hide(boolean isHidden) {
1212
        if (!shlConnect.isDisposed()){
1213
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1214
                shlConnect.setVisible(!isHidden);
1215
            }
1216
        }
1217
    }
1218

    
1219
    public void dispose() {
1220
        if (!shlConnect.isDisposed()){
1221
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1222
                shlConnect.dispose();
1223
            }
1224
        }
1225
    }
1226

    
1227
    public void onComplete() {
1228
        Display.getDefault().asyncExec(new Runnable() {
1229
            @Override
1230
            public void run() {
1231
                if(selectedCdmInstance!=null){
1232
                    if(isRememberMe()) {
1233
                        persistPrefCredentials();
1234
                    }else{
1235
                        removePrefCredentials();
1236
                    }
1237
                    persistPrefLastServerInstance();
1238
                }
1239
                dispose();
1240
            }
1241
        });
1242
    }
1243

    
1244
    private String generateLastModifiedTooltip(String cdmlibLastModified) {
1245
        if(StringUtils.isBlank(cdmlibLastModified)) {
1246
            return ""; //$NON-NLS-1$
1247
        }
1248
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.z"); //$NON-NLS-1$
1249
        Date cdmlibLastModifiedDate;
1250
        String cdmlibLastModifiedTimestamp = ""; //$NON-NLS-1$
1251

    
1252
        cdmlibLastModifiedDate = new Date(Long.valueOf(cdmlibLastModified));
1253
        cdmlibLastModifiedTimestamp = sdf.format(cdmlibLastModifiedDate);
1254

    
1255
        return cdmlibLastModifiedTimestamp;
1256
    }
1257

    
1258
    private void setEditorInfo() {
1259
        txtEditorCdmVersion.setText(CdmMetaData.getDbSchemaVersion());
1260
        setCdmlibVersion(txtEditorCdmlibVersion);
1261
    }
1262

    
1263
    private void setCdmlibVersion(Text txt) {
1264
        String editorVersionTimestamp = generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified());
1265
        txt.setText(CdmApplicationState.getCdmlibVersion() + ":" + editorVersionTimestamp); //$NON-NLS-1$
1266
    }
1267

    
1268
    private void clearOnServerChange() {
1269
        setMessage(""); //$NON-NLS-1$
1270
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1271
        txtServerCdmlibVersion.setText(""); //$NON-NLS-1$
1272
        txtServerCdmlibVersion.setToolTipText(""); //$NON-NLS-1$
1273
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1274
        comboCdmInstance.removeAll();
1275
        txtCdmInstanceStatus.setText(""); //$NON-NLS-1$
1276
        txtPort.setEditable(false);
1277
        txtPort.setEnabled(false);
1278
    }
1279

    
1280
    private void clearOnInstanceChange() {
1281
        setMessage(""); //$NON-NLS-1$
1282
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1283
        btnConnect.setText(LABEL_CONNECT);
1284
        btnConnect.setBackground(null);
1285
        btnConnect.requestLayout();
1286
    }
1287

    
1288
    @SuppressWarnings("unused")  //in work, for future centralized handling of control's status
1289
    private void updateControls(){
1290

    
1291
        //server
1292
//      comboCdmServer; //nothing to change
1293
        String strServerStatus = this.selectedServerInfo != null? STATUS_NOT_AVAILABLE : STATUS_AVAILABLE;
1294
        txtCdmServerStatus.setText(strServerStatus);
1295
//      btnCdmServerRefresh;  //nothing to change
1296

    
1297
        //database
1298
//        comboCdmInstance
1299
        String strInstanceStatus = this.selectedCdmInstance != null? STATUS_NOT_AVAILABLE : STATUS_AVAILABLE;
1300
        txtCdmInstanceStatus.setText(strInstanceStatus);
1301
//        btnCdmInstanceRefresh;  //nothing to change
1302

    
1303
        //login + connect
1304
        txtLogin.setText(Nz(login));
1305
        txtPassword.setText(Nz(password));
1306
        btnConnect.setText(LABEL_CONNECT);  //TODO
1307
        btnConnect.setEnabled(true);
1308

    
1309
        //rememberMe + defaultValues
1310
//        btnRememberMe;
1311
//        lblDefaultLogin;
1312

    
1313
        //message
1314
//        styledTxtMessage;
1315

    
1316
        //Advanced
1317
//        txtPort
1318
//        btnStopServer;
1319

    
1320
//        txtServerCdmlibVersion;
1321
//        txtEditorCdmlibVersion;
1322
//        txtServerSchemaVersion;
1323
//        txtEditorCdmVersion;
1324
    }
1325

    
1326
    private String Nz(String value) {
1327
        return CdmUtils.Nz(value);
1328
    }
1329
}
(5-5/8)