Project

General

Profile

Download (53.8 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2015 EDIT
3
 * European Distributed Institute of Taxonomy
4
 * http://www.e-taxonomy.eu
5
 *
6
 * The contents of this file are subject to the Mozilla Public License Version 1.1
7
 * See LICENSE.TXT at the top of this package for the full license terms.
8
 */
9
package eu.etaxonomy.taxeditor.ui.dialog;
10

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

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

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

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

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

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

    
104
    private final Map<String, CdmServerInfo> csiiMap = new HashMap<>();
105

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

    
115
    private final static String MESG_COMPATIBLE_EDITOR_OLD = Messages.RemotingLoginDialog_UPDATE_EDITOR;
116
    private final static String MESG_COMPATIBLE_SERVER_OLD = Messages.RemotingLoginDialog_CHOOSE_COMPATIBLE_CDM_SERVER;
117
    private final static String MESG_SCHEMA_MISSING = Messages.RemotingLoginDialog_SCHEMA_MISSING;
118
    private final static String MESG_NO_SCHEMA = Messages.RemotingLoginDialog_NO_SCHEMA;
119

    
120
    private final static String LABEL_CONNECT = Messages.RemotingLoginDialog_LABEL_CONNECT;
121
    private final static String LABEL_CREATE_SCHEMA = Messages.RemotingLoginDialog_LABEL_CREATE_SCHEMA;
122
    private final static String LABEL_UPDATE_SCHEMA_VERSION = Messages.RemotingLoginDialog_LABEL_UPDATE_SCHEMA_VERSION;
123
    private final static String MESG_UPDATE_SCHEMA_VERSION = Messages.RemotingLoginDialog_MSG_UPDATE_SCHEMA_VERSION;
124

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

    
127
    private final static String LOGIN_NODE = "login"; //$NON-NLS-1$
128
    private final static String USERNAME_SUFFIX = "_username"; //$NON-NLS-1$
129
    private final static String PASSWORD_SUFFIX = "_password"; //$NON-NLS-1$
130

    
131
    private final static String LAST_SERVER_INSTANCE_NODE = "lastServerInstance"; //$NON-NLS-1$
132
    private final static String LAST_SERVER_KEY = "lastServerKey"; //$NON-NLS-1$
133
    private final static String LAST_INSTANCE_KEY = "lastInstanceKey"; //$NON-NLS-1$
134

    
135
    private Composite remotingComposite;
136
    private CdmServerInfo selectedServerInfo;
137
    private CdmInstanceInfo selectedCdmInstance;
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 Composite compAdvanced;
148
    private Label lblPort;
149
    private Text txtPort;
150
    private Label lblServerCdmlibVersion;
151
    private Text txtServerCdmlibVersion;
152
    private ExpandableComposite expandableCompositeAdvanced;
153
    private StyledText styledTxtMessage;
154

    
155
//    private final int MIN_WIDTH = 530;
156
//    private final int MIN_HEIGHT = 220;
157
//    private final int MIN_EXP_HEIGHT = 380;
158

    
159
    private final int MESSAGE_HEIGHT = 50;
160
    private Label lblEditorCdmlibVersion;
161
    private Text txtEditorCdmlibVersion;
162
    private Label lblServerSchemaVersion;
163
    private Text txtServerSchemaVersion;
164
    private Label lblEditorCdmVersion;
165
    private Text txtEditorCdmVersion;
166

    
167
    private String serverName, instanceName;
168
    private boolean autoConnect = false;
169
    private boolean loadLoginPrefs = true;
170
    private boolean isDevRemoteSource = false;
171
    private Job serverJob;
172

    
173
    /**
174
     * Create the dialog.
175
     * @param parent
176
     * @param style
177
     */
178
    public RemotingLoginDialog(Shell parent, int style) {
179
        super(parent, style);
180
        setText(Messages.RemotingLoginDialog_LABEL_LOGIN);
181
    }
182

    
183
    public Object open(ICdmRemoteSource source, boolean loadLoginPrefs, boolean autoConnect) {
184
        this.loadLoginPrefs = loadLoginPrefs;
185
        this.serverName = source.getName();
186
        if (source instanceof CdmRemoteLocalhostSource){
187
            this.instanceName = ((CdmRemoteLocalhostSource)source).getDatasourceName();
188
        }else{
189
            String contextPath = source.getContext();
190
            this.instanceName = contextPath == null? "" : contextPath.substring(contextPath.lastIndexOf("/") + 1); //$NON-NLS-1$
191
        }
192
        return open(serverName, instanceName, loadLoginPrefs, autoConnect);
193
    }
194

    
195
    public Object open(String serverName, String instanceName, boolean loadLoginPrefs, boolean autoConnect) {
196
        this.serverName = serverName;
197
        this.instanceName = instanceName;
198
        this.loadLoginPrefs = loadLoginPrefs;
199
        this.autoConnect = autoConnect;
200
        return open();
201
    }
202

    
203
    /**
204
     * Open the dialog.
205
     * @return the dialog result
206
     */
207
    public Object open() {
208

    
209
        createContents();
210
        if(serverName == null && instanceName == null) {
211
            readPrefLastServerInstance();
212
        }
213

    
214
        setEditorInfo();
215
        populateCdmServerCombo();
216
        shlConnect.pack(true);
217
        shlConnect.open();
218

    
219
        expandableCompositeAdvanced.setExpanded(false);
220

    
221
        Display display = getParent().getDisplay();
222

    
223
        while (!shlConnect.isDisposed()) {
224
            if (!display.isDisposed()){
225
                if (!display.readAndDispatch()) {
226
                    display.sleep();
227
                }
228
            }
229
        }
230

    
231
        return result;
232
    }
233

    
234
    /**
235
     * Create contents of the dialog.
236
     */
237
    private void createContents() {
238
        shlConnect = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE);
239
        shlConnect.setText(LABEL_CONNECT);
240
        shlConnect.setLayout(new FillLayout(SWT.HORIZONTAL));
241

    
242
        remotingComposite = new Composite(shlConnect, SWT.NONE);
243
        remotingComposite.setLayout(new GridLayout(1, false));
244

    
245
        //server
246
        Composite cdmServerComposite = new Composite(remotingComposite, SWT.NONE);
247
        GridData gd_cdmServerComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
248
        cdmServerComposite.setLayoutData(gd_cdmServerComposite);
249
        cdmServerComposite.setLayout(new GridLayout(4, false));
250

    
251
        Label lblCdmServer = new Label(cdmServerComposite, SWT.NONE);
252
        lblCdmServer.setText(Messages.RemotingLoginDialog_LABEL_CDM_SERVER);
253
        lblCdmServer.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
254
        lblCdmServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
255

    
256
        comboCdmServer = new Combo(cdmServerComposite, SWT.READ_ONLY);
257
        comboCdmServer.addSelectionListener(new SelectionAdapter() {
258
            @Override
259
            public void widgetSelected(SelectionEvent e) {
260
                refreshCdmServer();
261
            }
262
        });
263
        GridData gd_comboCdmServer = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
264
        comboCdmServer.setLayoutData(gd_comboCdmServer);
265
        comboCdmServer.select(0);
266

    
267
        txtCdmServerStatus = new Text(cdmServerComposite, SWT.BORDER);
268
        txtCdmServerStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
269
        txtCdmServerStatus.setEditable(false);
270
        GridData gd_txtCdmServerStatus = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
271

    
272
        txtCdmServerStatus.setLayoutData(gd_txtCdmServerStatus);
273

    
274
        btnCdmServerRefresh = new Button(cdmServerComposite, SWT.NONE);
275
        btnCdmServerRefresh.addSelectionListener(new SelectionAdapter() {
276
            @Override
277
            public void widgetSelected(SelectionEvent e) {
278
                refreshCdmServer();
279
            }
280
        });
281
        btnCdmServerRefresh.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
282
        btnCdmServerRefresh.setText(Messages.RemotingLoginDialog_LABEL_REFRESH);
283

    
284
        //instance
285
        Label lblCdmInstance = new Label(cdmServerComposite, SWT.NONE);
286
        GridData gd_lblCdmInstance = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
287
        //gd_lblCdmInstance.heightHint = 30;
288
        lblCdmInstance.setLayoutData(gd_lblCdmInstance);
289
        lblCdmInstance.setText(Messages.RemotingLoginDialog_LABEL_CDM_INSTANCE);
290
        lblCdmInstance.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
291

    
292
        comboCdmInstance = new Combo(cdmServerComposite, SWT.READ_ONLY);
293
        comboCdmInstance.addSelectionListener(new SelectionAdapter() {
294
            @Override
295
            public void widgetSelected(SelectionEvent e) {
296
                refreshCdmInstance();
297
            }
298
        });
299
        GridData gd_comboCdmInstance = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
300
        comboCdmInstance.setLayoutData(gd_comboCdmInstance);
301
        comboCdmInstance.select(0);
302

    
303
        txtCdmInstanceStatus = new Text(cdmServerComposite, SWT.BORDER);
304
        txtCdmInstanceStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
305
        txtCdmInstanceStatus.setEditable(false);
306
        GridData gd_txtCdmInstanceStatus = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
307
        txtCdmInstanceStatus.setLayoutData(gd_txtCdmInstanceStatus);
308

    
309
        btnCdmInstanceRefresh = new Button(cdmServerComposite, SWT.FLAT);
310
        btnCdmInstanceRefresh.addSelectionListener(new SelectionAdapter() {
311
            @Override
312
            public void widgetSelected(SelectionEvent e) {
313
                refreshCdmInstance();
314
            }
315
        });
316
        GridData gd_btnCdmInstanceRefresh = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
317
        btnCdmInstanceRefresh.setLayoutData(gd_btnCdmInstanceRefresh);
318
        btnCdmInstanceRefresh.setText(Messages.RemotingLoginDialog_LABEL_REFRESH);
319

    
320
        //login
321
        loginComposite = new Composite(remotingComposite, SWT.NONE);
322
        GridData gd_loginComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
323
        loginComposite.setLayoutData(gd_loginComposite);
324
        GridLayout gl_loginComposite = new GridLayout(6, false);
325
        gl_loginComposite.marginTop = 5;
326
        loginComposite.setLayout(gl_loginComposite);
327

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

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

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

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

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

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

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

    
379
        styledTxtMessage = new StyledText(remotingComposite, SWT.NONE);
380
        styledTxtMessage.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
381
        styledTxtMessage.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
382
        styledTxtMessage.setFont(SWTResourceManager.getFont(UBUNTU, 12, SWT.BOLD));
383
        styledTxtMessage.setSelectionBackground(SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION_TEXT));
384
        styledTxtMessage.setSelectionForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
385
        styledTxtMessage.setDoubleClickEnabled(false);
386
        styledTxtMessage.setEditable(false);
387
        styledTxtMessage.setWordWrap(true);
388

    
389
        GridData gd_styledTxtMessage = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
390
        gd_styledTxtMessage.exclude = true;
391
        gd_styledTxtMessage.minimumHeight = MESSAGE_HEIGHT;
392

    
393
        styledTxtMessage.setLayoutData(gd_styledTxtMessage);
394

    
395
        //Advanced
396
        expandableCompositeAdvanced = new ExpandableComposite(remotingComposite, SWT.NONE, ExpandableComposite.TWISTIE);
397
        GridData gd_xpndblcmpstAdvanced = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1);
398
        expandableCompositeAdvanced.setLayoutData(gd_xpndblcmpstAdvanced);
399
        expandableCompositeAdvanced.addExpansionListener(new IExpansionListener() {
400
            @Override
401
            public void expansionStateChanged(ExpansionEvent e) {
402
                shlConnect.pack(true);
403
            }
404
            @Override
405
            public void expansionStateChanging(ExpansionEvent e) {
406
            }
407
        });
408
        expandableCompositeAdvanced.setText(Messages.RemotingLoginDialog_LABEL_ADVANCED);
409
        expandableCompositeAdvanced.setExpanded(true);
410

    
411
        compAdvanced = new Composite(expandableCompositeAdvanced, SWT.NONE);
412
        expandableCompositeAdvanced.setClient(compAdvanced);
413
        compAdvanced.setLayout(new GridLayout(4, false));
414

    
415
        lblPort = new Label(compAdvanced, SWT.CENTER);
416
        lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
417
        lblPort.setText(Messages.RemotingLoginDialog_LABEL_PORT);
418
        lblPort.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
419

    
420
        txtPort = new Text(compAdvanced, SWT.BORDER);
421
        GridData gd_txtPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
422
        gd_txtPort.minimumWidth = 50;
423
        txtPort.setLayoutData(gd_txtPort);
424

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

    
430
        txtServerCdmlibVersion = new Text(compAdvanced, SWT.BORDER);
431
        txtServerCdmlibVersion.setEditable(false);
432
        txtServerCdmlibVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
433

    
434
        btnStopServer = new Button(compAdvanced, SWT.FLAT);
435
        btnStopServer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
436
        btnStopServer.addMouseListener(new MouseAdapter() {
437
            @Override
438
            public void mouseUp(MouseEvent e) {
439
                stopManagedServer();
440
            }
441
        });
442
        btnStopServer.setText(Messages.RemotingLoginDialog_LABEL_STOP_MANAGED_SERVER);
443

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

    
449
        txtEditorCdmlibVersion = new Text(compAdvanced, SWT.BORDER);
450
        txtEditorCdmlibVersion.setEditable(false);
451
        txtEditorCdmlibVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
452
        addEmptyCells(2);
453

    
454
        lblServerSchemaVersion = new Label(compAdvanced, SWT.CENTER);
455
        lblServerSchemaVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
456
        lblServerSchemaVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDM_VERSION);
457
        lblServerSchemaVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
458

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

    
464
        lblEditorCdmVersion = new Label(compAdvanced, SWT.CENTER);
465
        lblEditorCdmVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
466
        lblEditorCdmVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDM_VERSION);
467
        lblEditorCdmVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
468

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

    
474
    @SuppressWarnings("unused")
475
    private void addEmptyCells(int cnt) {
476
        for (int i = 0; i < cnt; i++) {
477
            new Label(compAdvanced, SWT.NONE);
478
        }
479
    }
480

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

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

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

    
553
    private void updateSelectedCdmServer() {
554
        int selIndex = comboCdmServer.getSelectionIndex();
555
        if(selIndex != -1) {
556
            selectedServerInfo = csiiMap.get(comboCdmServer.getItem(selIndex));
557
        }
558
    }
559

    
560
    private void updatePort() {
561
        txtPort.setText(""); //$NON-NLS-1$
562
        if(selectedServerInfo != null) {
563
            int port = selectedServerInfo.getPort();
564
            if(port == CdmServerInfo.NULL_PORT) {
565
                txtPort.setText(CdmServerInfo.NULL_PORT_STRING);
566
            } else {
567
                txtPort.setText(String.valueOf(port));
568
            }
569
        }
570
    }
571

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

    
584
    private void checkSelectedCdmServer() {
585
        try{
586
            if(selectedServerInfo != null) {
587
                if(selectedServerInfo.isLocalhost()) {
588
                    txtPort.setEditable(true);
589
                    txtPort.setEnabled(true);
590
                    setCdmlibVersion(txtServerCdmlibVersion);
591
                }
592
                try {
593
                    if(selectedServerInfo.pingServer()) {
594
                        txtCdmServerStatus.setText(STATUS_AVAILABLE);
595
                        populateCdmInstanceCombo(true);
596
                        String serverVersionTimestamp = generateLastModifiedTooltip(selectedServerInfo.getCdmlibLastModified());
597
                        txtServerCdmlibVersion.setText(selectedServerInfo.getCdmlibServicesVersion() + ":" + serverVersionTimestamp); //$NON-NLS-1$
598
                    } else {
599
                        txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
600
                        comboCdmInstance.removeAll();
601
                        disableCdmInstanceControls("", ""); //$NON-NLS-1$ //$NON-NLS-2$
602
                    }
603
                } catch (CdmServerException | IOException e) {
604
                    txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
605
                    // TODO distinguish java.net.ConnectException: Connection refused, java.net.SocketTimeoutException: Read timed out
606
                    Throwable cause = e;
607
                    if(e instanceof CdmServerException && e.getCause() != null){
608
                        cause = e.getCause();
609
                    }
610
                    String message = Messages.RemotingLoginDialog_CONNECTION_FAILED_MESSAGE;
611
                    if(cause instanceof SocketTimeoutException){
612
                        message = Messages.RemotingLoginDialog_CONNECTION_TIMEOUT_MESSAGE;
613
                    }
614
                    MessagingUtils.warningDialog(Messages.RemotingLoginDialog_CONNECTION_FAILED_TITLE, this,
615
                            message);
616
                    logger.warn(Messages.RemotingLoginDialog_CONNECTION_FAILED_TITLE, e);
617
                }
618
            }
619
            updatePort();
620
        }
621
        catch(SWTException e){
622
            //catch widget is disposed exception which may occurr if
623
            //dialog is closed but the runnable tries to update
624
        }
625
    }
626

    
627
    private void populateCdmInstanceCombo(final boolean forceRefresh) {
628
        comboCdmInstance.removeAll();
629
        comboCdmInstance.setEnabled(false);
630
        btnConnect.setEnabled(false);
631
        txtCdmInstanceStatus.setText(STATUS_RETRIEVING);
632
        txtCdmInstanceStatus.setToolTipText(""); //$NON-NLS-1$
633

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

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

    
686
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE) && !isDevRemoteSource) {
687
            // Start the Job
688
            serverJob.schedule();
689
        }
690
    }
691

    
692
    private void disableCdmInstanceControls(String cdmInstanceStatus, String tooltip) {
693
        txtCdmInstanceStatus.setText(cdmInstanceStatus);
694
        txtCdmInstanceStatus.setToolTipText(tooltip);
695
        comboCdmInstance.setEnabled(false);
696
        btnConnect.setEnabled(false);
697

    
698
    }
699

    
700
    private void refreshCdmInstance() {
701
        txtCdmInstanceStatus.setText(STATUS_CHECKING_AVAILABILITY);
702
        clearOnInstanceChange();
703
        updateSelectedCdmInstance();
704
        checkSelectedCdmInstance();
705
        updateManagedServerControls();
706
    }
707

    
708
    private void updateSelectedCdmInstance() {
709
        int selIndex = comboCdmInstance.getSelectionIndex();
710
        if(selIndex != -1) {
711
            selectedCdmInstance = selectedServerInfo.getInstanceFromName(comboCdmInstance.getItem(selIndex));
712
            if(loadLoginPrefs) {
713
                readPrefCredentials();
714
            }
715
        }
716
    }
717

    
718
    private void updateManagedServerControls() {
719
        if(selectedServerInfo.isLocalhostMgd()) {
720
            if(isSelectedCdmInstanceRunningInManagedServer()) {
721
                txtCdmInstanceStatus.setText(STATUS_STARTED);
722
            } else {
723
                txtCdmInstanceStatus.setText(STATUS_NOT_STARTED);
724
            }
725
            btnConnect.setEnabled(true);
726
            selectedServerInfo.setPort(getManagedServerPort());
727
            updatePort();
728
        }
729

    
730
        if(isManagedServerRunning()) {
731
            btnStopServer.setEnabled(true);
732
        } else {
733
            btnStopServer.setEnabled(false);
734
        }
735
    }
736

    
737
    private boolean isManagedServerRunning() {
738
        return CdmStore.getManagedServer() != null && CdmStore.getManagedServer().isAlive();
739
    }
740

    
741
    private boolean isSelectedCdmInstanceRunningInManagedServer() {
742
        return CdmStore.getManagedServer() != null &&
743
                CdmStore.getManagedServer().isAlive() &&
744
                selectedServerInfo.isLocalhostMgd() &&
745
                CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName());
746
    }
747

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

    
762
        boolean forceSchemaCreate = !schemaExists(selectedCdmInstance);
763
        boolean forceSchemaUpdate = LABEL_UPDATE_SCHEMA_VERSION.equals(btnConnect.getText());
764

    
765
        Job job = new Job(Messages.RemotingLoginDialog_JOB_SERVER_LAUNCH) {
766

    
767
            @Override
768
            public IStatus run(IProgressMonitor monitor) {
769
                String mgdServerConfigFileName = "mgd.datasources.xml"; //$NON-NLS-1$
770
                String config = CdmServerUtils.convertEditorToServerConfig();
771
                int maxUnits = 50;
772
                monitor.beginTask(Messages.RemotingLoginDialog_TASK_LAUNCHING_SERVER, maxUnits);
773
                try {
774
                    monitor.subTask(String.format(Messages.RemotingLoginDialog_GENERATING_CONFIG_FILE, selectedCdmInstance.getName()));
775
                    File managedServerConfigFile = CdmServerUtils.writeManagedServerConfig(config, mgdServerConfigFileName);
776
                    monitor.worked(1);
777
                    CdmServer cdmServer = new CdmServer(selectedCdmInstance.getName(), managedServerConfigFile);
778
//                    boolean forceSchemaCreate = CdmStore.getManagedServer() != null
779
//                            && CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())
780
//                            && CdmStore.getManagedServer().isForceSchemaCreate();
781
                    cdmServer.setForceSchemaCreate(forceSchemaCreate);
782
                    cdmServer.setForceSchemaUpdate(forceSchemaUpdate);
783
                    CdmStore.setManagedServer(cdmServer);
784
                    monitor.subTask(Messages.RemotingLoginDialog_STARTING_MGD_SERVER);
785
                    cdmServer.start(false, RemotingLoginDialog.this);
786
                    int serverUnits = 0;
787

    
788
                    // the following loop is a 'fake' progress monitoring where the progress
789
                    // bar is advanced by one unit every second until maxUnits -2
790
                    while(!CdmStore.getManagedServer().isStarted() && !CdmStore.getManagedServer().isFailed()) {
791
                        if(serverUnits < maxUnits - 2) {
792
                            try {
793
                                Thread.sleep(1000);
794
                            } catch (InterruptedException e) {
795
                            }
796
                            monitor.worked(1);
797
                            serverUnits++;
798
                        }
799
                    }
800
                    Display.getDefault().syncExec(()->{
801
                                hide(false);
802
                                updateManagedServerControls();
803
                                connect();
804
                    });
805
                } catch (IOException ioe) {
806
                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_GENERATING_CONFIG_FILE,
807
                            this,
808
                            ioe.getMessage(),
809
                            TaxeditorStorePlugin.PLUGIN_ID,
810
                            ioe,
811
                            true);
812
                } catch (CdmEmbeddedServerException cese) {
813
                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STARTING_SERVER,
814
                            this,
815
                            cese.getMessage(),
816
                            TaxeditorStorePlugin.PLUGIN_ID,
817
                            cese,
818
                            true);
819
                } finally {
820
                    monitor.done();
821
                }
822
                // NOTE: Errors thrown during server startup are passed to the handleError() implementation
823
                // TODO: is the above catch clause for CDMEmbeddedServerException still valuable?
824

    
825
                return Status.OK_STATUS;
826
            }
827
       };
828

    
829
        // configure the job
830
        job.setProperty(IProgressConstants.KEEP_PROPERTY, true);
831
        job.setUser(true);
832
        // schedule job
833
        hide(true);
834
        job.schedule();
835
    }
836

    
837
    private boolean schemaExists(CdmInstanceInfo instanceInfo) {
838
        if (instanceInfo.getDataSource() != null){
839
            try {
840
                //TODO we need a new method in cdmlib to check for existing schema
841
                String schemaVersion = instanceInfo.getDataSource().getDbSchemaVersion();
842
                return schemaVersion != null;
843
            } catch (CdmSourceException e) {
844
                return false;
845
            }
846
        }else{
847
            return true;
848
        }
849
    }
850

    
851
    private String managedSchemaVersion(CdmInstanceInfo instanceInfo) throws CdmSourceException{
852
        if (instanceInfo.getDataSource() != null){
853
            return instanceInfo.getDataSource().getDbSchemaVersion();
854
        }else{
855
            throw new RuntimeException("ManagedSchemaVersion only available for managed server instances.");
856
        }
857
    }
858
    private int compareSchemaVersion(CdmInstanceInfo instanceInfo) throws CdmSourceException {
859
        return CdmMetaData.compareVersion(managedSchemaVersion(instanceInfo), CdmMetaData.getDbSchemaVersion(), 3, null);
860
    }
861

    
862
    @Override
863
    public void handleError(final Throwable t) {
864

    
865
        if(CdmStore.getManagedServer().isFailed() && CdmStore.getManagedServer().isPotentiallyMissingSchema()) {
866
            CdmStore.getManagedServer().setForceSchemaCreate(true);
867
            // we are in a separate thread here, thus update the screen via
868
            checkManagedSelectedInstance();
869
        } else {
870
            Display.getDefault().syncExec(new Runnable() {
871
                @Override
872
                public void run() {
873
                    serverJob.cancel();
874

    
875
                    String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
876
                    String  message = t.getMessage();
877

    
878
                    MessagingUtils.errorDialog(title,
879
                            this,
880
                            message,
881
                            TaxeditorStorePlugin.PLUGIN_ID,
882
                            t,
883
                            true);
884
                }
885
            });
886
        }
887
    }
888

    
889
    private void stopManagedServer() {
890
        try {
891
            CdmStore.getManagedServer().stop();
892
        } catch (Exception e) {
893
            MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STOPPING_SERVER,
894
                    this,
895
                    String.format(Messages.RemotingLoginDialog_COULD_NOT_STOP_SERVER, CdmStore.getManagedServer().getPort()),
896
                    TaxeditorStorePlugin.PLUGIN_ID,
897
                    e,
898
                    true);
899
        }
900
        CdmStore.setManagedServer(null);
901
        updateManagedServerControls();
902
    }
903

    
904
    private int getManagedServerPort() {
905
        return CdmStore.getManagedServer() == null ? CdmServerInfo.NULL_PORT : CdmStore.getManagedServer().getPort();
906
    }
907

    
908
    private void checkSelectedCdmInstance() {
909

    
910
        if (selectedServerInfo.isLocalhostMgd()){
911
            checkManagedSelectedInstance();
912
        }else if (txtCdmServerStatus.getText().equals(STATUS_AVAILABLE)) {
913
            boolean available = false;
914
            String instanceStatus = STATUS_NOT_AVAILABLE;
915
            String message = null;
916
            try {
917
                if(selectedServerInfo.pingInstance(selectedCdmInstance, getPort())) {
918
                    instanceStatus = STATUS_AVAILABLE;
919
                    available = true;
920
                } else {
921
                    instanceStatus = STATUS_NOT_AVAILABLE;
922
                    available = false;
923
                }
924

    
925
                if(available) {
926
                    txtServerSchemaVersion.setText(selectedServerInfo.getCdmRemoteSource(selectedCdmInstance, getPort()).getDbSchemaVersion());
927

    
928
                    int compareDbSchemaVersion = selectedServerInfo.compareDbSchemaVersion(selectedCdmInstance, getPort());
929

    
930
                    int compareCdmlibServicesVersion = 0;
931
                    boolean disableServicesApiTimestampCheck =
932
                            PreferencesUtil.getBooleanValue((IPreferenceKeys.DISABLE_SERVICES_API_TIMESTAMP_CHECK));
933
                    if(!disableServicesApiTimestampCheck) {
934
                        compareCdmlibServicesVersion = selectedServerInfo.compareCdmlibServicesVersion();
935
                    }
936

    
937
                    if(compareDbSchemaVersion > 0 || compareCdmlibServicesVersion > 0) {
938
                        instanceStatus = STATUS_NOT_COMPATIBLE;
939
                        available = false;
940
                        message = MESG_COMPATIBLE_EDITOR_OLD;
941
                    } else if(compareDbSchemaVersion < 0 || compareCdmlibServicesVersion < 0) {
942
                        instanceStatus = STATUS_NOT_COMPATIBLE;
943
                        available = false;
944
                        message = MESG_COMPATIBLE_SERVER_OLD;
945
                    } else {
946
                        instanceStatus =  STATUS_AVAILABLE;
947
                        available = true;
948
                        message = ""; //$NON-NLS-1$
949
                    }
950
                }
951
            } catch (Exception e) {
952
                txtCdmInstanceStatus.setToolTipText(e.getMessage());
953
            } finally {
954
                btnConnect.setEnabled(available);
955
                txtCdmInstanceStatus.setText(instanceStatus);
956
                if(!StringUtils.isBlank(message)) {
957
                    setMessage(message);
958
                }
959
            }
960
        }
961
    }
962

    
963
    private void checkManagedSelectedInstance() {
964
        boolean available = false;
965
        String instanceStatus = STATUS_NOT_AVAILABLE;
966
        String message = null;
967
        String connect = LABEL_CONNECT;
968
        int color = SWT.COLOR_BLACK;
969
        String schemaVersion = CdmMetaData.getDbSchemaVersion();
970

    
971
        if (!schemaExists(selectedCdmInstance)){
972
            message = MESG_SCHEMA_MISSING;
973
            connect = LABEL_CREATE_SCHEMA;
974
            color = SWT.COLOR_RED;
975
            schemaVersion = MESG_NO_SCHEMA;
976
        } else {
977
            int compare;
978
            try {
979
                schemaVersion = managedSchemaVersion(selectedCdmInstance);
980
                compare = compareSchemaVersion(selectedCdmInstance);
981
                if (compare > 0){
982
                    instanceStatus = STATUS_NOT_COMPATIBLE;
983
                    message = MESG_COMPATIBLE_EDITOR_OLD;
984
                    available = false;
985
                }else if (compare < 0){
986
                    instanceStatus = STATUS_NOT_COMPATIBLE;
987
                    message = MESG_UPDATE_SCHEMA_VERSION;
988
                    available = true;
989
                    connect = LABEL_UPDATE_SCHEMA_VERSION;
990
                    color = SWT.COLOR_RED;
991
                }else{
992
                    available = true;
993
                    instanceStatus = STATUS_AVAILABLE;
994
                }
995
            } catch (CdmSourceException e) {
996
                available = false;
997
            }
998
        }
999

    
1000
        setManagedValues(available, instanceStatus, connect, color, schemaVersion);
1001
        setMessage(message);
1002
    }
1003

    
1004
    private void setManagedValues(boolean available, String instanceStatus, String connect, int color,
1005
            String schemaVersion) {
1006
        Display.getDefault().syncExec(()->{
1007
            btnConnect.setEnabled(available);
1008
            btnConnect.setText(connect);
1009
            btnConnect.setBackground(Display.getCurrent().getSystemColor(color));
1010
            btnConnect.requestLayout();
1011
            txtCdmInstanceStatus.setText(instanceStatus);
1012
            txtServerSchemaVersion.setText(schemaVersion);
1013
         });
1014
    }
1015

    
1016
    private void connect() {
1017
        checkSelectedCdmInstance();
1018

    
1019
        if(!txtCdmInstanceStatus.getText().equals(STATUS_AVAILABLE)) {
1020
            return;
1021
        }
1022

    
1023
        ICdmRemoteSource source = selectedServerInfo.getCdmRemoteSource(selectedCdmInstance, getPort());
1024

    
1025
        if(!validateLogin(source)) {
1026
            return;
1027
        }
1028

    
1029
        try {
1030
            CdmStore.connect(source, this);
1031
        } catch (Exception e) {
1032
            // Do not expect anything to go wrong at this point, so we throw a runtime exception
1033
            // if any problems
1034
            throw new RuntimeException(e);
1035
        }
1036
    }
1037

    
1038
    public boolean isRememberMe() {
1039
        return btnRememberMe.getSelection();
1040
    }
1041

    
1042
    private void persistPrefLastServerInstance() {
1043
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1044
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
1045

    
1046
        lastServerInstancePrefs.put(LAST_SERVER_KEY, selectedServerInfo.getName());
1047
        lastServerInstancePrefs.put(LAST_INSTANCE_KEY, selectedCdmInstance.getName());
1048

    
1049
        flushPreferences(lastServerInstancePrefs);
1050
    }
1051

    
1052
    private void persistPrefCredentials() {
1053
         IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1054
         Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1055
         credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
1056
         credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
1057
         flushPreferences(credentialsPrefs);
1058
    }
1059

    
1060
    private void removePrefCredentials() {
1061
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1062
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1063
        credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
1064
        credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
1065
        removePreferences(credentialsPrefs);
1066
    }
1067

    
1068
    private void removePreferences(Preferences prefs) {
1069
        try {
1070
            prefs.removeNode();
1071
        } catch (BackingStoreException bse) {
1072
            setMessage(bse.getMessage());
1073
        }
1074
    }
1075

    
1076
    private void flushPreferences(Preferences prefs) {
1077
        try {
1078
            prefs.flush();
1079
        } catch (BackingStoreException bse) {
1080
            setMessage(bse.getMessage());
1081
        }
1082
    }
1083

    
1084
    private void readPrefCredentials() {
1085
        String username, password;
1086
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1087
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1088
        username = credentialsPrefs.get(getUsernamePrefKey(), ""); //$NON-NLS-1$
1089
        txtLogin.setText(username);
1090
        password = credentialsPrefs.get(getPasswordPrefKey(),""); //$NON-NLS-1$
1091
        txtPassword.setText(password);
1092
        if(username.isEmpty() || password.isEmpty()) {
1093
            autoConnect = false;
1094
        }
1095
    }
1096

    
1097
    private void readPrefLastServerInstance() {
1098
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1099
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
1100

    
1101
        serverName = lastServerInstancePrefs.get(LAST_SERVER_KEY, null);
1102
        instanceName = lastServerInstancePrefs.get(LAST_INSTANCE_KEY, null);
1103
    }
1104

    
1105
    private void emptyCredentials() {
1106
        txtLogin.setText(""); //$NON-NLS-1$
1107
        txtPassword.setText(""); //$NON-NLS-1$
1108
    }
1109

    
1110
    private String getUsernamePrefKey() {
1111
        return selectedServerInfo.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + USERNAME_SUFFIX;
1112
    }
1113

    
1114
    private String getPasswordPrefKey() {
1115
        return selectedServerInfo.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + PASSWORD_SUFFIX;
1116
    }
1117

    
1118
    private boolean validateLogin(ICdmRemoteSource remoteSource) {
1119
        if(getUsername() == null || getUsername().isEmpty()) {
1120
            setMessage(Messages.RemotingLoginDialog_LOGIN_CANNOT_BE_EMPTY);
1121
            return false;
1122
        }
1123
        if(getPassword() == null || getPassword().isEmpty()) {
1124
            setMessage(Messages.RemotingLoginDialog_PASSWORD_CANNOT_BE_EMPTY);
1125
            return false;
1126
        }
1127

    
1128
        try {
1129
            IUserService userService = CdmApplicationRemoteConfiguration.getUserService(remoteSource);
1130
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(getUsername(), getPassword());
1131
            CdmApplicationRemoteConfiguration.getAuthenticationManager(userService).authenticate(token);
1132
        } catch(BadCredentialsException e){
1133
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1134
            return false;
1135
        } catch(LockedException e){
1136
            setMessage(LoginManager.ACCOUNT_LOCKED_MESSAGE);
1137
            return false;
1138
        } catch(IllegalArgumentException e){
1139
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1140
            return false;
1141
        }
1142
        return true;
1143
    }
1144

    
1145
    public String getUsername() {
1146
        return txtLogin.getText();
1147
    }
1148

    
1149
    public String getPassword() {
1150
        return txtPassword.getText();
1151
    }
1152

    
1153
    public void setMessage(String message) {
1154
        if(CdmUtils.isNotBlank(message)) {
1155
//            if(message.length() > 50) {
1156
//                styledTxtMessage.setToolTipText(message);
1157
//                message = message.substring(0,50) + "..."; //$NON-NLS-1$
1158
//            }
1159
            styledTxtMessage.setText(message);
1160
            styledTxtMessage.setVisible(true);
1161
            ((GridData)styledTxtMessage.getLayoutData()).exclude = false;
1162
//            shlConnect.setMinimumSize(MIN_WIDTH, getHeightWithoutMessage() + MESSAGE_HEIGHT);
1163
            shlConnect.pack(true);
1164
        } else {
1165
            if (!styledTxtMessage.isDisposed()){
1166
                styledTxtMessage.setText(""); //$NON-NLS-1$
1167
                styledTxtMessage.setVisible(false);
1168
                ((GridData)styledTxtMessage.getLayoutData()).exclude = true;
1169
            }
1170
            if(!shlConnect.isDisposed()){
1171
                shlConnect.pack(true);
1172
            }
1173
        }
1174
        if (!remotingComposite.isDisposed()){
1175
            remotingComposite.layout();
1176
        }
1177
    }
1178

    
1179
//    private int getHeightWithoutMessage() {
1180
//        if(xpndblcmpstAdvanced.isExpanded()) {
1181
//            return MIN_EXP_HEIGHT;
1182
//        } else {
1183
//            return MIN_HEIGHT;
1184
//        }
1185
//    }
1186

    
1187
    public void hide(boolean isHidden) {
1188
        if (!shlConnect.isDisposed()){
1189
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1190
                shlConnect.setVisible(!isHidden);
1191
            }
1192
        }
1193
    }
1194

    
1195
    public void dispose() {
1196
        if (!shlConnect.isDisposed()){
1197
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1198
                shlConnect.dispose();
1199
            }
1200
        }
1201
    }
1202

    
1203
    public void onComplete() {
1204
        Display.getDefault().asyncExec(new Runnable() {
1205
            @Override
1206
            public void run() {
1207
                if(selectedCdmInstance!=null){
1208
                    if(isRememberMe()) {
1209
                        persistPrefCredentials();
1210
                    }else{
1211
                        removePrefCredentials();
1212
                    }
1213
                    persistPrefLastServerInstance();
1214
                }
1215
                dispose();
1216
            }
1217
        });
1218
    }
1219

    
1220
    private String generateLastModifiedTooltip(String cdmlibLastModified) {
1221
        if(StringUtils.isBlank(cdmlibLastModified)) {
1222
            return ""; //$NON-NLS-1$
1223
        }
1224
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.z"); //$NON-NLS-1$
1225
        Date cdmlibLastModifiedDate;
1226
        String cdmlibLastModifiedTimestamp = ""; //$NON-NLS-1$
1227

    
1228
        cdmlibLastModifiedDate = new Date(Long.valueOf(cdmlibLastModified));
1229
        cdmlibLastModifiedTimestamp = sdf.format(cdmlibLastModifiedDate);
1230

    
1231
        return cdmlibLastModifiedTimestamp;
1232
    }
1233

    
1234
    private void setEditorInfo() {
1235
        txtEditorCdmVersion.setText(CdmMetaData.getDbSchemaVersion());
1236
        setCdmlibVersion(txtEditorCdmlibVersion);
1237
        String editorVersionTimestamp = generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified());
1238
        txtEditorCdmlibVersion.setText(CdmApplicationState.getCdmlibVersion() + ":" + editorVersionTimestamp); //$NON-NLS-1$
1239
    }
1240

    
1241
    private void setCdmlibVersion(Text txt) {
1242
        String editorVersionTimestamp = generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified());
1243
        txt.setText(CdmApplicationState.getCdmlibVersion() + ":" + editorVersionTimestamp); //$NON-NLS-1$
1244
    }
1245

    
1246
    private void clearOnServerChange() {
1247
        setMessage(""); //$NON-NLS-1$
1248
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1249
        txtServerCdmlibVersion.setText(""); //$NON-NLS-1$
1250
        txtServerCdmlibVersion.setToolTipText(""); //$NON-NLS-1$
1251
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1252
        comboCdmInstance.removeAll();
1253
        txtCdmInstanceStatus.setText(""); //$NON-NLS-1$
1254
        txtPort.setEditable(false);
1255
        txtPort.setEnabled(false);
1256
    }
1257

    
1258
    private void clearOnInstanceChange() {
1259
        setMessage(""); //$NON-NLS-1$
1260
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1261
    }
1262
}
(5-5/8)