Project

General

Profile

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

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

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

    
80
/**
81
 * @author cmathew
82
 * @date 20 Jan 2015
83
 */
84
public class RemotingLoginDialog extends Dialog implements ICdmServerError {
85

    
86
    private Logger logger = Logger.getLogger(getClass());
87

    
88
    public static final String DEFAULT_PASS = "00000"; //$NON-NLS-1$
89
    public static final String DEFAULT_USER = "admin"; //$NON-NLS-1$
90

    
91
    public final static String STATUS_AVAILABLE = Messages.RemotingLoginDialog_STATUS_AVAILABLE;
92
    public final static String STATUS_NOT_AVAILABLE = Messages.RemotingLoginDialog_STATUS_NOT_AVAILABLE;
93
    public final static String STATUS_STARTED = Messages.RemotingLoginDialog_STATUS_STARTED;
94
    public final static String STATUS_NOT_STARTED = Messages.RemotingLoginDialog_STATUS_NOT_STARTED;
95
    public final static String STATUS_RETRIEVING = Messages.RemotingLoginDialog_STATUS_RETRIEVING;
96
    public final static String STATUS_CHECKING_AVAILABILITY = Messages.RemotingLoginDialog_STATUS_CHECKING;
97
    public final static String STATUS_NO_INSTANCES = Messages.RemotingLoginDialog_STATUS_NO_INSTANCES_FOUND;
98
    public final static String STATUS_NOT_COMPATIBLE = Messages.RemotingLoginDialog_STATUS_NOT_COMPATIBLE;
99

    
100
    public final static String MESG_COMPATIBLE_EDITOR_OLD = Messages.RemotingLoginDialog_UPDATE_EDITOR;
101
    public final static String MESG_COMPATIBLE_SERVER_OLD = Messages.RemotingLoginDialog_CHOOSE_COMPATIBLE_CDM_SERVER;
102
    public final static String MESG_SCHEMA_MISSING = Messages.RemotingLoginDialog_SCHEMA_MISSING;
103
    public final static String MESG_NO_SCHEMA = Messages.RemotingLoginDialog_NO_SCHEMA;
104

    
105
    public final static String LABEL_CONNECT = Messages.RemotingLoginDialog_LABEL_CONNECT;
106
    public final static String LABEL_CREATE_SCHEMA = Messages.RemotingLoginDialog_LABEL_CREATE_SCHEMA;
107
    public final static String LABEL_UPDATE_SCHEMA_VERSION = Messages.RemotingLoginDialog_LABEL_UPDATE_SCHEMA_VERSION;
108
    public final static String MESG_UPDATE_SCHEMA_VERSION = Messages.RemotingLoginDialog_MSG_UPDATE_SCHEMA_VERSION;
109
    public final static String LABEL_LOGIN = Messages.RemotingLoginDialog_LABEL_LOGIN;
110
    public final static String LABEL_CDM_SERVER = Messages.RemotingLoginDialog_LABEL_CDM_SERVER;
111
    public final static String LABEL_REFRESH = Messages.RemotingLoginDialog_LABEL_REFRESH;
112
    public final static String LABEL_CDM_INSTANCE = Messages.RemotingLoginDialog_LABEL_CDM_INSTANCE;
113
    public final static String LABEL_LOGIN_COLON = Messages.RemotingLoginDialog_LABEL_LOGIN_COLON;
114
    public final static String LABEL_PASSWORD = Messages.RemotingLoginDialog_LABEL_PASSWORD;
115
    public final static String LABEL_EDITOR_CDM_VERSION = Messages.RemotingLoginDialog_LABEL_EDITOR_CDM_VERSION;
116
    public final static String LABEL_SERVER_CDM_VERSION = Messages.RemotingLoginDialog_LABEL_SERVER_CDM_VERSION;
117
    public final static String LABEL_EDITOR_CDMLIB_VERSION = Messages.RemotingLoginDialog_LABEL_EDITOR_CDMLIB_VERSION;
118
    public final static String LABEL_SERVER_CDMLIB_VERSION = Messages.RemotingLoginDialog_LABEL_SERVER_CDMLIB_VERSION;
119
    public final static String LABEL_STOP_MANAGED_SERVER = Messages.RemotingLoginDialog_LABEL_STOP_MANAGED_SERVER;
120
    public final static String LABEL_PORT = Messages.RemotingLoginDialog_LABEL_PORT;
121
    public final static String LABEL_ADVANCED = Messages.RemotingLoginDialog_LABEL_ADVANCED;
122
    public final static String LABEL_DEFAULT_LOGIN = Messages.RemotingLoginDialog_DEFAULT_LOGIN;
123
    public final static String LABEL_REMEMBER_ME = Messages.RemotingLoginDialog_LABEL_REMEMBER_ME;
124

    
125
    public final static String MESG_LOGIN_CANNOT_BE_EMPTY = Messages.RemotingLoginDialog_LOGIN_CANNOT_BE_EMPTY;
126
    public final static String STATUS_GENERATING_CONFIG_FILE = Messages.RemotingLoginDialog_GENERATING_CONFIG_FILE;
127
    public final static String STATUS_STARTING_MGD_SERVER = Messages.RemotingLoginDialog_STARTING_MGD_SERVER;
128

    
129
    public final static String ERR_GENERATING_CONFIG_FILE = Messages.RemotingLoginDialog_ERROR_GENERATING_CONFIG_FILE;
130
    public final static String ERR_STARTING_SERVER = Messages.RemotingLoginDialog_ERROR_STARTING_SERVER;
131
    public final static String ERR_SERVER_LAUNCH = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
132
    public final static String ERR_STOPPING_SERVER = Messages.RemotingLoginDialog_ERROR_STOPPING_SERVER;
133
    public final static String ERR_COULD_NOT_STOP_SERVER = Messages.RemotingLoginDialog_COULD_NOT_STOP_SERVER;
134
    public final static String RETRIEVE_SERVER_INSTANCES = Messages.RemotingLoginDialog_RETRIEVE_SERVER_INSTANCES;
135
    public final static String TASK_LAUNCHING_SERVER = Messages.RemotingLoginDialog_TASK_LAUNCHING_SERVER;
136

    
137
    public static final int BTN_COLOR_ATTENTION = SWT.COLOR_RED;
138

    
139
    public final static String STORE_PREFERENCES_NODE = "eu.etaxonomy.taxeditor.store"; //$NON-NLS-1$
140

    
141
    public final static String LOGIN_NODE = "login"; //$NON-NLS-1$
142
    public final static String USERNAME_SUFFIX = "_username"; //$NON-NLS-1$
143
    public final static String PASSWORD_SUFFIX = "_password"; //$NON-NLS-1$
144

    
145
    public final static String LAST_SERVER_INSTANCE_NODE = "lastServerInstance"; //$NON-NLS-1$
146
    public final static String LAST_SERVER_KEY = "lastServerKey"; //$NON-NLS-1$
147
    public final static String LAST_INSTANCE_KEY = "lastInstanceKey"; //$NON-NLS-1$
148

    
149
    protected Shell shlConnect;
150
    protected Text txtCdmServerStatus;
151
    protected Text txtCdmInstanceStatus;
152
    protected Combo comboCdmServer;
153
    protected Combo comboCdmInstance;
154
    protected Button btnConnect;
155

    
156
    protected Composite remotingComposite;
157
    protected Button btnCdmServerRefresh;
158
    protected Button btnCdmInstanceRefresh;
159
    protected Button btnStopServer;
160
    protected Composite loginComposite;
161
    protected Label lblLogin;
162
    protected Text txtLogin;
163
    protected Label lblPassword;
164
    protected Text txtPassword;
165
    protected Button btnRememberMe;
166
    protected Label lblDefaultLogin;
167
    protected Composite compAdvanced;
168
    protected Label lblPort;
169
    protected Text txtPort;
170
    protected Label lblServerCdmlibVersion;
171
    protected Text txtServerCdmlibVersion;
172
    protected ExpandableComposite expandableCompositeAdvanced;
173
    protected StyledText styledTxtMessage;
174

    
175
    protected Label lblEditorCdmlibVersion;
176
    protected Text txtEditorCdmlibVersion;
177
    protected Label lblServerSchemaVersion;
178
    protected Text txtServerSchemaVersion;
179
    protected Label lblEditorCdmVersion;
180
    protected Text txtEditorCdmVersion;
181

    
182
    protected final int MESSAGE_HEIGHT = 50;
183
    protected final int COMBO_MIN_WIDTH =200;
184
    protected final int CONTROLS_MIN_HEIGHT = 23; //does not seem to work yet
185
//  private final int MIN_EXP_HEIGHT = 380;
186

    
187
    protected boolean autoConnect = false;
188
    protected boolean loadLoginPrefs = true;
189
    protected boolean isDevRemoteSource = false;
190
    protected boolean isLocal = false;
191

    
192
    protected Job serverJob;
193
    protected Object result;
194

    
195
    protected final Map<String, CdmServerInfo> serverInfoMap = new HashMap<>();
196

    
197
    protected String serverName;
198
    protected String instanceName;
199
    protected CdmServerInfo selectedServerInfo;
200
    protected CdmInstanceInfo selectedCdmInstance;
201
    protected String login;
202
    protected String password;
203

    
204
    /**
205
     * Create the dialog.
206
     * @param parent
207
     * @param style
208
     */
209
    public RemotingLoginDialog(Shell parent, int style) {
210
        super(parent, style);
211
        setText(LABEL_LOGIN);
212
    }
213

    
214
    public Object open(ICdmRemoteSource source, boolean loadLoginPrefs, boolean autoConnect) {
215
        this.loadLoginPrefs = loadLoginPrefs;
216
        this.setServerName(source.getName());
217
        if (source instanceof CdmRemoteLocalhostSource){
218
            this.setInstanceName(((CdmRemoteLocalhostSource)source).getDatasourceName());
219
        }else{
220
            String contextPath = source.getContext();
221
            this.setInstanceName(contextPath == null? "" : contextPath.substring(contextPath.lastIndexOf("/") + 1)); //$NON-NLS-1$
222
        }
223
        return open(getServerName(), getInstanceName(), loadLoginPrefs, autoConnect);
224
    }
225

    
226
    public Object open(String serverName, String instanceName, boolean loadLoginPrefs, boolean autoConnect) {
227
        this.setServerName(serverName);
228
        this.setInstanceName(instanceName);
229
        this.loadLoginPrefs = loadLoginPrefs;
230
        this.setAutoConnect(autoConnect);
231
        return open();
232
    }
233

    
234
    /**
235
     * Open the dialog.
236
     * @return the dialog result
237
     */
238
    public Object open() {
239

    
240
        createContents();
241
        if(getServerName() == null && getInstanceName() == null) {
242
            readPrefLastServerInstance();
243
        }
244
        expandableCompositeAdvanced.setExpanded(false);
245

    
246
        setEditorInfo();
247
        populateCdmServerCombo();
248
        shlConnect.pack(true);
249

    
250
        setCenterPoint();
251
        shlConnect.open();
252

    
253
        Display display = getParent().getDisplay();
254
        while (!shlConnect.isDisposed()) {
255
            if (!display.isDisposed()){
256
                if (!display.readAndDispatch()) {
257
                    display.sleep();
258
                }
259
            }
260
        }
261
        return result;
262
    }
263

    
264
    /**
265
     * Create contents of the dialog.
266
     */
267
    protected void createContents() {
268
        shlConnect = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE | SWT.CENTER);
269
        shlConnect.setText(LABEL_CONNECT);
270
        shlConnect.setLayout(new FillLayout(SWT.HORIZONTAL));
271

    
272
        remotingComposite = new Composite(shlConnect, SWT.NONE);
273
        remotingComposite.setLayout(new GridLayout(1, false));
274

    
275
        //server
276
        Composite cdmServerComposite = new Composite(remotingComposite, SWT.NONE);
277
        GridData gd_cdmServerComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
278
        cdmServerComposite.setLayoutData(gd_cdmServerComposite);
279
        cdmServerComposite.setLayout(new GridLayout(4, false));
280

    
281
        Label lblCdmServer = new Label(cdmServerComposite, SWT.NONE);
282
        lblCdmServer.setText(LABEL_CDM_SERVER);
283
        lblCdmServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
284

    
285
        comboCdmServer = new Combo(cdmServerComposite, SWT.READ_ONLY);
286
        comboCdmServer.addSelectionListener(new SelectionAdapter() {
287
            @Override
288
            public void widgetSelected(SelectionEvent e) {
289
                onRefreshCdmServer();
290
            }
291
        });
292

    
293
        GridData gd_comboCdmServer = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
294

    
295
        comboCdmServer.setLayoutData(gd_comboCdmServer);
296
        comboCdmServer.select(0);
297

    
298
        txtCdmServerStatus = new Text(cdmServerComposite, SWT.BORDER);
299
        txtCdmServerStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
300
        txtCdmServerStatus.setEditable(false);
301
        GridData gd_txtCdmServerStatus = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
302
        gd_txtCdmServerStatus.minimumHeight = CONTROLS_MIN_HEIGHT;
303
        txtCdmServerStatus.setLayoutData(gd_txtCdmServerStatus);
304

    
305
        btnCdmServerRefresh = new Button(cdmServerComposite, SWT.NONE);
306
        btnCdmServerRefresh.addSelectionListener(new SelectionAdapter() {
307
            @Override
308
            public void widgetSelected(SelectionEvent e) {
309
                onRefreshCdmServer();
310
            }
311
        });
312
        GridData gd_btnCdmServerRefresh = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
313
        gd_btnCdmServerRefresh.minimumHeight = CONTROLS_MIN_HEIGHT;
314
        btnCdmServerRefresh.setLayoutData(gd_btnCdmServerRefresh);
315
        btnCdmServerRefresh.setText(LABEL_REFRESH);
316

    
317
        //instance
318
        Label lblCdmInstance = new Label(cdmServerComposite, SWT.NONE);
319
        GridData gd_lblCdmInstance = new GridData(SWT.RIGHT, SWT.CENTER, false, true, 1, 1);
320
        //gd_lblCdmInstance.heightHint = 30;
321
        lblCdmInstance.setLayoutData(gd_lblCdmInstance);
322
        lblCdmInstance.setText(LABEL_CDM_INSTANCE);
323

    
324
        comboCdmInstance = new Combo(cdmServerComposite, SWT.READ_ONLY);
325
        comboCdmInstance.addSelectionListener(new SelectionAdapter() {
326
            @Override
327
            public void widgetSelected(SelectionEvent e) {
328
                onRefreshCdmInstance();
329
            }
330
        });
331

    
332
        GridData gd_comboCdmInstance = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
333
        gd_comboCdmInstance.minimumWidth = COMBO_MIN_WIDTH;
334

    
335
        comboCdmInstance.setLayoutData(gd_comboCdmInstance);
336
        comboCdmInstance.select(0);
337

    
338
        txtCdmInstanceStatus = new Text(cdmServerComposite, SWT.BORDER);
339
        txtCdmInstanceStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
340
        txtCdmInstanceStatus.setEditable(false);
341
        GridData gd_txtCdmInstanceStatus = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
342
        gd_txtCdmInstanceStatus.minimumHeight = CONTROLS_MIN_HEIGHT;
343
        txtCdmInstanceStatus.setLayoutData(gd_txtCdmInstanceStatus);
344

    
345
        btnCdmInstanceRefresh = new Button(cdmServerComposite, SWT.FLAT);
346
        btnCdmInstanceRefresh.addSelectionListener(new SelectionAdapter() {
347
            @Override
348
            public void widgetSelected(SelectionEvent e) {
349
                onRefreshCdmInstance();
350
            }
351
        });
352
        GridData gd_btnCdmInstanceRefresh = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
353
        gd_btnCdmInstanceRefresh.minimumHeight = CONTROLS_MIN_HEIGHT;
354
        btnCdmInstanceRefresh.setLayoutData(gd_btnCdmInstanceRefresh);
355
        btnCdmInstanceRefresh.setText(Messages.RemotingLoginDialog_LABEL_REFRESH);
356

    
357
        //login + connect
358
        loginComposite = new Composite(remotingComposite, SWT.NONE);
359
        GridData gd_loginComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
360
        loginComposite.setLayoutData(gd_loginComposite);
361
        GridLayout gl_loginComposite = new GridLayout(6, false);
362
        gl_loginComposite.marginTop = 5;
363
        loginComposite.setLayout(gl_loginComposite);
364

    
365
        lblLogin = new Label(loginComposite, SWT.CENTER);
366
        GridData gd_lblLogin = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
367
        lblLogin.setLayoutData(gd_lblLogin);
368
        lblLogin.setText(Messages.RemotingLoginDialog_LABEL_LOGIN_COLON);
369

    
370
        txtLogin = new Text(loginComposite, SWT.BORDER);
371
        GridData gd_txtLogin = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
372
        gd_txtLogin.minimumWidth = 80;
373
        txtLogin.setLayoutData(gd_txtLogin);
374

    
375
        lblPassword = new Label(loginComposite, SWT.CENTER);
376
        lblPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
377
        lblPassword.setText(Messages.RemotingLoginDialog_LABEL_PASSWORD);
378

    
379
        txtPassword = new Text(loginComposite, SWT.BORDER | SWT.PASSWORD);
380
        GridData gd_txtPassword = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
381
        gd_txtPassword.minimumWidth = 80;
382
        txtPassword.setLayoutData(gd_txtPassword);
383
        @SuppressWarnings("unused")
384
        Label nope = new Label(loginComposite, SWT.NONE);
385
        txtPassword.addKeyListener(new KeyAdapter() {
386
        	@Override
387
        	public void keyPressed(KeyEvent e) {
388
        		if(e.character==SWT.CR){
389
        		    if(btnConnect.getText().equals(LABEL_CONNECT)){
390
                        onConnectButtonPressed();
391
                    }
392
        		}
393
        	}
394
        });
395

    
396
        btnConnect = new Button(loginComposite, SWT.FLAT);
397
        btnConnect.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
398
        btnConnect.addSelectionListener(new SelectionAdapter() {
399
			@Override
400
			public void widgetSelected(SelectionEvent e) {
401
				onConnectButtonPressed();
402
			}
403
		});
404
        btnConnect.setText(LABEL_CONNECT);
405

    
406
        //rememberMe + default values
407
        btnRememberMe = new Button(loginComposite, SWT.CHECK);
408
        btnRememberMe.setSelection(true);
409
        GridData gd_btnRememberMe = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1);
410
        btnRememberMe.setLayoutData(gd_btnRememberMe);
411
        btnRememberMe.setText(Messages.RemotingLoginDialog_LABEL_REMEMBER_ME);
412

    
413
        lblDefaultLogin = new Label(loginComposite, SWT.NONE);
414
        GridDataFactory.fillDefaults().span(4, 1).align(SWT.TRAIL, SWT.CENTER).applyTo(lblDefaultLogin);
415
        lblDefaultLogin.setText(String.format(Messages.RemotingLoginDialog_DEFAULT_LOGIN, DEFAULT_USER, DEFAULT_PASS));
416
        lblDefaultLogin.setVisible(false);
417

    
418
        styledTxtMessage = new StyledText(remotingComposite, SWT.NONE);
419
        styledTxtMessage.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
420
        styledTxtMessage.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
421
        styledTxtMessage.setSelectionBackground(SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION_TEXT));
422
        styledTxtMessage.setSelectionForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
423
        styledTxtMessage.setDoubleClickEnabled(false);
424
        styledTxtMessage.setEditable(false);
425
        styledTxtMessage.setWordWrap(true);
426

    
427
        GridData gd_styledTxtMessage = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
428
        gd_styledTxtMessage.exclude = true;
429
        gd_styledTxtMessage.minimumHeight = MESSAGE_HEIGHT;
430

    
431
        styledTxtMessage.setLayoutData(gd_styledTxtMessage);
432

    
433
        //Advanced
434
        expandableCompositeAdvanced = new ExpandableComposite(remotingComposite, SWT.NONE, ExpandableComposite.TWISTIE);
435
        GridData gd_xpndblcmpstAdvanced = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1);
436
        expandableCompositeAdvanced.setLayoutData(gd_xpndblcmpstAdvanced);
437
        expandableCompositeAdvanced.addExpansionListener(new IExpansionListener() {
438
            @Override
439
            public void expansionStateChanged(ExpansionEvent e) {
440
                shlConnect.pack(true);
441
            }
442
            @Override
443
            public void expansionStateChanging(ExpansionEvent e) {
444
            }
445
        });
446
        expandableCompositeAdvanced.setText(Messages.RemotingLoginDialog_LABEL_ADVANCED);
447
        expandableCompositeAdvanced.setExpanded(true);
448

    
449
        compAdvanced = new Composite(expandableCompositeAdvanced, SWT.NONE);
450
        expandableCompositeAdvanced.setClient(compAdvanced);
451
        compAdvanced.setLayout(new GridLayout(4, false));
452

    
453
        lblPort = new Label(compAdvanced, SWT.CENTER);
454
        lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
455
        lblPort.setText(Messages.RemotingLoginDialog_LABEL_PORT);
456

    
457
        txtPort = new Text(compAdvanced, SWT.BORDER);
458
        GridData gd_txtPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
459
        gd_txtPort.minimumWidth = 50;
460
        txtPort.setLayoutData(gd_txtPort);
461

    
462
        lblServerCdmlibVersion = new Label(compAdvanced, SWT.CENTER);
463
        lblServerCdmlibVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
464
        lblServerCdmlibVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDMLIB_VERSION);
465

    
466
        txtServerCdmlibVersion = new Text(compAdvanced, SWT.BORDER);
467
        txtServerCdmlibVersion.setEditable(false);
468
        txtServerCdmlibVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
469
/*
470
        btnStopServer = new Button(compAdvanced, SWT.FLAT);
471
        btnStopServer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
472
        btnStopServer.addMouseListener(new MouseAdapter() {
473
            @Override
474
            public void mouseUp(MouseEvent e) {
475
                onStopManagedServer();
476
            }
477
        });
478
        btnStopServer.setText(Messages.RemotingLoginDialog_LABEL_STOP_MANAGED_SERVER);
479
*/
480
        lblEditorCdmlibVersion = new Label(compAdvanced, SWT.CENTER);
481
        lblEditorCdmlibVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
482
        lblEditorCdmlibVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDMLIB_VERSION);
483

    
484
        txtEditorCdmlibVersion = new Text(compAdvanced, SWT.BORDER);
485
        txtEditorCdmlibVersion.setEditable(false);
486
        txtEditorCdmlibVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
487
        addEmptyCells(2);
488

    
489
        lblServerSchemaVersion = new Label(compAdvanced, SWT.CENTER);
490
        lblServerSchemaVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
491
        lblServerSchemaVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDM_VERSION);
492

    
493
        txtServerSchemaVersion = new Text(compAdvanced, SWT.BORDER);
494
        txtServerSchemaVersion.setEditable(false);
495
        txtServerSchemaVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
496
        addEmptyCells(2);
497

    
498
        lblEditorCdmVersion = new Label(compAdvanced, SWT.CENTER);
499
        lblEditorCdmVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
500
        lblEditorCdmVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDM_VERSION);
501

    
502
        txtEditorCdmVersion = new Text(compAdvanced, SWT.BORDER);
503
        txtEditorCdmVersion.setEditable(false);
504
        txtEditorCdmVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
505
    }
506

    
507
    public void setCenterPoint() {
508
        Rectangle parentSize = getParent().getBounds();
509
        Rectangle shellSize = shlConnect.getBounds();
510
        int locationX = (parentSize.width - shellSize.width)/2+parentSize.x;
511
        int locationY = (parentSize.height - shellSize.height)/2+parentSize.y;
512
        shlConnect.setLocation(new Point(locationX, locationY));
513

    
514
    }
515

    
516

    
517

    
518

    
519

    
520

    
521
    @SuppressWarnings("unused")
522
    private void addEmptyCells(int cnt) {
523
        for (int i = 0; i < cnt; i++) {
524
            new Label(compAdvanced, SWT.NONE);
525
        }
526
    }
527

    
528
	protected void onConnectButtonPressed() {
529
		/*if(selectedServerInfo.isLocalhostMgd() && !isSelectedCdmInstanceRunningInManagedServer()) {
530
			startManagedServer();
531
		} else {*/
532
			connect();
533
			if (CdmStore.isActive() && CdmStore.currentAuthentiationHasOneOfRoles(Role.ROLE_REMOTING)){
534
			    PreferencesUtil.setNomenclaturalCodePreferences();
535
			}
536
//		}
537
	}
538

    
539
    protected void populateCdmServerCombo() {
540
        Job job = new Job(RETRIEVE_SERVER_INSTANCES) {
541
            @Override
542
            protected IStatus run(IProgressMonitor monitor) {
543
                Display.getDefault().syncExec(new Runnable() {
544
                    @Override
545
                    public void run() {
546
                        //TODO performance
547
                        putAllServers();
548
                        int serverIndex = -1;
549
                        if(getServerName() != null) {
550
                            serverIndex = comboCdmServer.indexOf(getServerName());
551
                        }
552
                        if(serverIndex == -1) {
553
                            comboCdmServer.select(0);
554
                            setAutoConnect(false);
555
                        } else {
556
                            comboCdmServer.select(serverIndex);
557
                        }
558
                        ICdmSource devRemoteSource = CdmServerInfo.getDevServerRemoteSource();
559
                        if(devRemoteSource != null) {
560
                            setDevRemoteSource(true);
561
                            String username = System.getProperty("cdm.server.dev.username"); //$NON-NLS-1$
562
                            String password = System.getProperty("cdm.server.dev.password"); //$NON-NLS-1$
563
                            if(username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
564
                                txtLogin.setText(username);
565
                                txtPassword.setText(password);
566
                                CdmStore.connect(devRemoteSource, RemotingLoginDialog.this);
567
                            }
568
                        } else {
569
                            onRefreshCdmServer();
570
                        }
571
                    }
572

    
573

    
574
                });
575
                return Status.OK_STATUS;
576
            }
577
        };
578
        job.schedule();
579
    }
580
    public void putAllServers() {
581
        for(CdmServerInfo csii : CdmServerInfo.getCdmServers(isLocal)) {
582
            putServerInfo(csii);
583
            comboCdmServer.add(csii.getName());
584
        }
585
    }
586

    
587
    public void putServerInfo(CdmServerInfo csii) {
588
        getServerInfoMap().put(csii.getName(), csii);
589
    }
590
    public void onRefreshCdmServer() {
591
        try{
592
            txtCdmServerStatus.setText(STATUS_CHECKING_AVAILABILITY);
593
            clearOnServerChange();
594
            emptyCredentials();
595
            updateSelectedCdmServer();
596
            Display.getDefault().asyncExec(new Runnable() {
597
                @Override
598
                public void run() {
599
                    checkSelectedCdmServer();
600
                }
601
            });
602
        }
603
        catch(SWTException e){
604
            //catch widget is disposed exception which may occur if
605
            //dialog is closed but the runnable tries to update
606
        }
607
    }
608

    
609
    protected void updateSelectedCdmServer() {
610
        int selIndex = comboCdmServer.getSelectionIndex();
611
        if(selIndex != -1) {
612
            selectedServerInfo = getServerInfoMap().get(comboCdmServer.getItem(selIndex));
613
        }
614
    }
615

    
616
    protected void updatePort() {
617
        txtPort.setText(""); //$NON-NLS-1$
618
        if(selectedServerInfo != null) {
619
            int port = selectedServerInfo.getPort();
620
            if(port == CdmServerInfo.NULL_PORT) {
621
                txtPort.setText(CdmServerInfo.NULL_PORT_STRING);
622
            } else {
623
                txtPort.setText(String.valueOf(port));
624
            }
625
        }
626
    }
627

    
628
    protected int getPort() {
629
        int port = CdmServerInfo.NULL_PORT;
630
        try {
631
            port = Integer.valueOf(txtPort.getText());
632
        } catch (NumberFormatException nfe) {
633
            if(!CdmServerInfo.NULL_PORT_STRING.equals(txtPort.getText())) {
634
                setMessage(Messages.RemotingLoginDialog_MESSAGE_PORT_SHOULD_BE_INTEGER);
635
            }
636
        }
637
        return port;
638
    }
639

    
640
    private void checkSelectedCdmServer() {
641
        try{
642
            if(selectedServerInfo != null) {
643
                if(selectedServerInfo.isLocalhost()) {
644
                    txtPort.setEditable(true);
645
                    txtPort.setEnabled(true);
646
                }
647
                try {
648
                    if(selectedServerInfo.pingServer()) {
649
                        txtCdmServerStatus.setText(STATUS_AVAILABLE);
650
                        populateCdmInstanceCombo(true);
651
                        if(selectedServerInfo.isLocalhost()){
652
                            setCdmlibVersion(txtServerCdmlibVersion);
653
                        }else{
654
                            String serverVersionTimestamp = generateLastModifiedTooltip(selectedServerInfo.getCdmlibLastModified());
655
                            txtServerCdmlibVersion.setText(selectedServerInfo.getCdmlibServicesVersion() + ":" + serverVersionTimestamp); //$NON-NLS-1$
656
                        }
657
                    } else {
658
                        txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
659
                        comboCdmInstance.removeAll();
660
                        disableCdmInstanceControls("", ""); //$NON-NLS-1$ //$NON-NLS-2$
661
                    }
662
                } catch (CdmServerException | IOException e) {
663
                    txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
664
                    // TODO distinguish java.net.ConnectException: Connection refused, java.net.SocketTimeoutException: Read timed out
665
                    Throwable cause = e;
666
                    if(e instanceof CdmServerException && e.getCause() != null){
667
                        cause = e.getCause();
668
                    }
669
                    String message = Messages.RemotingLoginDialog_CONNECTION_FAILED_MESSAGE;
670
                    if(cause instanceof SocketTimeoutException){
671
                        message = Messages.RemotingLoginDialog_CONNECTION_TIMEOUT_MESSAGE;
672
                    }
673
                    MessagingUtils.warningDialog(Messages.RemotingLoginDialog_CONNECTION_FAILED_TITLE, this,
674
                            message);
675
                    logger.warn(Messages.RemotingLoginDialog_CONNECTION_FAILED_TITLE, e);
676
                }
677
            }
678
            updatePort();
679
        }
680
        catch(SWTException e){
681
            //catch widget is disposed exception which may occur if
682
            //dialog is closed but the runnable tries to update
683
        }
684
    }
685

    
686
    protected void populateCdmInstanceCombo(final boolean forceRefresh) {
687
        comboCdmInstance.removeAll();
688
        comboCdmInstance.setEnabled(false);
689
        btnConnect.setEnabled(false);
690
        txtCdmInstanceStatus.setText(STATUS_RETRIEVING);
691
        txtCdmInstanceStatus.setToolTipText(""); //$NON-NLS-1$
692

    
693
        serverJob = new Job(Messages.RemotingLoginDialog_RETRIEVE_SERVER_INSTANCES) {
694
            @Override
695
            protected IStatus run(IProgressMonitor monitor) {
696
                try {
697
                    if(selectedServerInfo != null) {
698
                        if(forceRefresh) {
699
                            selectedServerInfo.refreshInstances();
700
                        }
701
                        final List<CdmInstanceInfo> instances = selectedServerInfo.getInstances();
702
                        Display.getDefault().asyncExec(new Runnable() {
703
                            @Override
704
                            public void run() {
705
                                if(!instances.isEmpty()) {
706
                                    for(CdmInstanceInfo cdmInstance : instances) {
707
                                        comboCdmInstance.add(cdmInstance.getName());
708
                                    }
709
                                    int instanceIndex = -1;
710
                                    if(getInstanceName() != null) {
711
                                        instanceIndex = comboCdmInstance.indexOf(getInstanceName());
712
                                    }
713
                                    if(instanceIndex == -1) {
714
                                        comboCdmInstance.select(0);
715
                                        setAutoConnect(false);
716
                                    } else {
717
                                        comboCdmInstance.select(instanceIndex);
718
                                    }
719
                                    onRefreshCdmInstance();
720
                                    comboCdmInstance.setEnabled(true);
721
                                    if(isAutoConnect()) {
722
                                        connect();
723
                                    }
724
                                } else {
725
                                    txtCdmInstanceStatus.setText(STATUS_NO_INSTANCES);
726
                                    btnConnect.setEnabled(false);
727
                                }
728
                            }
729
                        });
730
                    }
731
                } catch (final CdmServerException e) {
732
                    MessagingUtils.warn(getClass(), e);
733
                    Display.getDefault().asyncExec(new Runnable() {
734
                        @Override
735
                        public void run() {
736
                            disableCdmInstanceControls(STATUS_NOT_AVAILABLE, e.getMessage());
737
                        }
738
                    });
739
                }
740
                return Status.OK_STATUS;
741
            }
742
        };
743

    
744
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE) && !isDevRemoteSource()) {
745
            // Start the Job
746
            serverJob.schedule();
747
        }
748
    }
749

    
750
    public void disableCdmInstanceControls(String cdmInstanceStatus, String tooltip) {
751
        txtCdmInstanceStatus.setText(cdmInstanceStatus);
752
        txtCdmInstanceStatus.setToolTipText(tooltip);
753
        comboCdmInstance.setEnabled(false);
754
        btnConnect.setEnabled(false);
755
    }
756

    
757
    public void onRefreshCdmInstance() {
758
        txtCdmInstanceStatus.setText(STATUS_CHECKING_AVAILABILITY);
759
        clearOnInstanceChange();
760
        updateSelectedCdmInstance();
761
        checkSelectedCdmInstance();
762
//        updateManagedServerControls();
763
    }
764

    
765
    protected void updateSelectedCdmInstance() {
766
        int selIndex = comboCdmInstance.getSelectionIndex();
767
        if(selIndex != -1) {
768
            selectedCdmInstance = selectedServerInfo.getInstanceFromName(comboCdmInstance.getItem(selIndex));
769
            if(loadLoginPrefs) {
770
                readPrefCredentials();
771
            }
772
        }
773
    }
774
/*
775
    private void updateManagedServerControls() {
776
        if(selectedServerInfo.isLocalhostMgd()) {
777
            if(isSelectedCdmInstanceRunningInManagedServer()) {
778
                txtCdmInstanceStatus.setText(STATUS_STARTED);
779
            } else {
780
                txtCdmInstanceStatus.setText(STATUS_NOT_STARTED);
781
            }
782
            btnConnect.setEnabled(true);
783
            selectedServerInfo.setPort(getManagedServerPort());
784
            updatePort();
785
        }
786

    
787
        if(isManagedServerRunning()) {
788
            btnStopServer.setEnabled(true);
789
        } else {
790
            btnStopServer.setEnabled(false);
791
        }
792
    }
793

    
794
    private boolean isManagedServerRunning() {
795
        return CdmStore.getManagedServer() != null && CdmStore.getManagedServer().isAlive();
796
    }
797

    
798
    private boolean isSelectedCdmInstanceRunningInManagedServer() {
799
        return CdmStore.getManagedServer() != null &&
800
                CdmStore.getManagedServer().isAlive() &&
801
                selectedServerInfo.isLocalhostMgd() &&
802
                CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName());
803
    }
804

    
805
    private void startManagedServer() {
806
        /*if(isManagedServerRunning()) {
807
            if(CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())) {
808
                return;
809
            } else {
810
                Display.getDefault().syncExec(new Runnable() {
811
                    @Override
812
                    public void run() {
813
                        onStopManagedServer();
814
                    }
815
                });
816
            }
817
        }
818
        boolean forceSchemaCreate = !schemaExists(selectedCdmInstance);
819
        boolean forceSchemaUpdate = LABEL_UPDATE_SCHEMA_VERSION.equals(btnConnect.getText());
820

    
821
        Job job = new Job(Messages.RemotingLoginDialog_JOB_SERVER_LAUNCH) {
822

    
823
            @Override
824
            public IStatus run(IProgressMonitor monitor) {
825
                String mgdServerConfigFileName = "mgd.datasources.xml"; //$NON-NLS-1$
826
                String config = CdmServerUtils.convertEditorToServerConfig();
827
                int maxUnits = 50;
828
                monitor.beginTask(Messages.RemotingLoginDialog_TASK_LAUNCHING_SERVER, maxUnits);
829
                try {
830
                    monitor.subTask(String.format(Messages.RemotingLoginDialog_GENERATING_CONFIG_FILE, selectedCdmInstance.getName()));
831
                    File managedServerConfigFile = CdmServerUtils.writeManagedServerConfig(config, mgdServerConfigFileName);
832
                    monitor.worked(1);
833
                    CdmServer cdmServer = new CdmServer(selectedCdmInstance.getName(), managedServerConfigFile);
834
                    cdmServer.setForceSchemaCreate(forceSchemaCreate);
835
                    cdmServer.setForceSchemaUpdate(forceSchemaUpdate);
836
                    CdmStore.setManagedServer(cdmServer);
837
                    monitor.subTask(Messages.RemotingLoginDialog_STARTING_MGD_SERVER);
838
                    cdmServer.start(false, RemotingLoginDialog.this);
839
                    int serverUnits = 0;
840

    
841
                    // the following loop is a 'fake' progress monitoring where the progress
842
                    // bar is advanced by one unit every second until maxUnits -2
843
                    while(!CdmStore.getManagedServer().isStarted() && !CdmStore.getManagedServer().isFailed()) {
844
                        if(serverUnits < maxUnits - 2) {
845
                            try {
846
                                Thread.sleep(1000);
847
                            } catch (InterruptedException e) {
848
                            }
849
                            monitor.worked(1);
850
                            serverUnits++;
851
                        }
852
                    }
853
                    Display.getDefault().syncExec(()->{
854
                                hide(false);
855
                                updateManagedServerControls();
856
                                connect();
857
                    });
858
                } catch (IOException ioe) {
859
                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_GENERATING_CONFIG_FILE,
860
                            this,
861
                            ioe.getMessage(),
862
                            TaxeditorStorePlugin.PLUGIN_ID,
863
                            ioe,
864
                            true);
865
                } catch (CdmEmbeddedServerException cese) {
866
                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STARTING_SERVER,
867
                            this,
868
                            cese.getMessage(),
869
                            TaxeditorStorePlugin.PLUGIN_ID,
870
                            cese,
871
                            true);
872
                } finally {
873
                    monitor.done();
874
                }
875
                // NOTE: Errors thrown during server startup are passed to the handleError() implementation
876
                // TODO: is the above catch clause for CdmEmbeddedServerException still valuable?
877

    
878
                return Status.OK_STATUS;
879
            }
880
       };
881

    
882
        // configure the job
883
        job.setProperty(IProgressConstants.KEEP_PROPERTY, true);
884
        job.setUser(true);
885
        // schedule job
886
        hide(true);
887
        job.schedule();
888
    }
889
    */
890
    private boolean schemaExists(CdmInstanceInfo instanceInfo) {
891
        if (instanceInfo.getDataSource() != null){
892
            try {
893
                //TODO we need a new method in cdmlib to check for existing schema
894
                String schemaVersion = instanceInfo.getDataSource().getDbSchemaVersion();
895
                return schemaVersion != null;
896
            } catch (CdmSourceException e) {
897
                return false;
898
            }
899
        }else{
900
            return true;
901
        }
902
    }
903

    
904
    private String managedSchemaVersion(CdmInstanceInfo instanceInfo) throws CdmSourceException{
905
        if (instanceInfo.getDataSource() != null){
906
            return instanceInfo.getDataSource().getDbSchemaVersion();
907
        }else{
908
            throw new RuntimeException("ManagedSchemaVersion only available for managed server instances.");
909
        }
910
    }
911
    private int compareSchemaVersion(CdmInstanceInfo instanceInfo) throws CdmSourceException {
912
        return CdmMetaData.compareVersion(managedSchemaVersion(instanceInfo), CdmMetaData.getDbSchemaVersion(), 3, null);
913
    }
914
/*
915
    @Override
916
    public void handleError(final Throwable t) {
917

    
918
        Display.getDefault().syncExec(()-> {
919
            serverJob.cancel();
920

    
921
            String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
922
            String  message = t.getMessage();
923

    
924
            MessagingUtils.errorDialog(title,
925
                    this,
926
                    message,
927
                    TaxeditorStorePlugin.PLUGIN_ID,
928
                    t,
929
                    true);
930
        });
931
    }
932

    
933
    private void onStopManagedServer() {
934
        try {
935
            CdmStore.getManagedServer().stop();
936
        } catch (Exception e) {
937
            MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STOPPING_SERVER,
938
                    this,
939
                    String.format(Messages.RemotingLoginDialog_COULD_NOT_STOP_SERVER, CdmStore.getManagedServer().getPort()),
940
                    TaxeditorStorePlugin.PLUGIN_ID,
941
                    e,
942
                    true);
943
        }
944
        CdmStore.setManagedServer(null);
945
        updateManagedServerControls();
946
    }
947

    
948
    private int getManagedServerPort() {
949
        return CdmStore.getManagedServer() == null ? CdmServerInfo.NULL_PORT : CdmStore.getManagedServer().getPort();
950
    }
951
*/
952
    protected void checkSelectedCdmInstance() {
953
        try {
954
            if (selectedCdmInstance != null && selectedCdmInstance.getDataSource() != null){
955
                String schemaVersion = selectedCdmInstance.getDataSource().getDbSchemaVersion();
956
            }
957
        } catch (CdmSourceException e1) {
958
            // TODO Auto-generated catch block
959
            e1.printStackTrace();
960
        }
961
       if (txtCdmServerStatus.getText().equals(STATUS_AVAILABLE)) {
962

    
963
            boolean available = false;
964
            String instanceStatus = STATUS_NOT_AVAILABLE;
965
            String message = null;
966
            try {
967
                if(selectedServerInfo.pingInstance(selectedCdmInstance, getPort())) {
968
                    instanceStatus = STATUS_AVAILABLE;
969
                    available = true;
970
                } else {
971
                    instanceStatus = STATUS_NOT_AVAILABLE;
972
                    available = false;
973
                }
974

    
975
                if(available) {
976
                    txtServerSchemaVersion.setText(selectedServerInfo.getCdmRemoteSource(selectedCdmInstance, getPort()).getDbSchemaVersion());
977

    
978
                    int compareDbSchemaVersion = selectedServerInfo.compareDbSchemaVersion(selectedCdmInstance, getPort());
979

    
980
                    int compareCdmlibServicesVersion = 0;
981
                    boolean disableServicesApiTimestampCheck =
982
                            PreferencesUtil.getBooleanValue((IPreferenceKeys.DISABLE_SERVICES_API_TIMESTAMP_CHECK));
983
                    if(!disableServicesApiTimestampCheck) {
984
                        compareCdmlibServicesVersion = selectedServerInfo.compareCdmlibServicesVersion();
985
                    }
986

    
987
                    if(compareDbSchemaVersion > 0 || compareCdmlibServicesVersion > 0) {
988
                        instanceStatus = STATUS_NOT_COMPATIBLE;
989
                        available = false;
990
                        message = MESG_COMPATIBLE_EDITOR_OLD;
991
                    } else if(compareDbSchemaVersion < 0 || compareCdmlibServicesVersion < 0) {
992
                        instanceStatus = STATUS_NOT_COMPATIBLE;
993
                        available = false;
994
                        message = MESG_COMPATIBLE_SERVER_OLD;
995
                    } else {
996
                        instanceStatus =  STATUS_AVAILABLE;
997
                        available = true;
998
                        message = ""; //$NON-NLS-1$
999
                    }
1000
                }
1001
            } catch (Exception e) {
1002
                txtCdmInstanceStatus.setToolTipText(e.getMessage());
1003
            } finally {
1004
                lblDefaultLogin.setVisible(false);
1005
                btnConnect.setEnabled(available);
1006
                txtCdmInstanceStatus.setText(instanceStatus);
1007
                if(!StringUtils.isBlank(message)) {
1008
                    setMessage(message);
1009
                }
1010
            }
1011
        }
1012
    }
1013

    
1014
//    private void checkManagedSelectedInstance() {
1015
//        boolean available = false;
1016
//        String instanceStatus = STATUS_NOT_AVAILABLE;
1017
//        String message = null;
1018
//        String connect = LABEL_CONNECT;
1019
//        Integer color = null;
1020
//        String schemaVersion = CdmMetaData.getDbSchemaVersion();
1021
//
1022
//        if (!schemaExists(selectedCdmInstance)){
1023
//            message = MESG_SCHEMA_MISSING;
1024
//            connect = LABEL_CREATE_SCHEMA;
1025
//            color = BTN_COLOR_ATTENTION;
1026
//            schemaVersion = MESG_NO_SCHEMA;
1027
//        } else {
1028
//            int compare;
1029
//            try {
1030
//                schemaVersion = managedSchemaVersion(selectedCdmInstance);
1031
//                compare = compareSchemaVersion(selectedCdmInstance);
1032
//                if (compare > 0){
1033
//                    instanceStatus = STATUS_NOT_COMPATIBLE;
1034
//                    message = MESG_COMPATIBLE_EDITOR_OLD;
1035
//                    available = false;
1036
//                }else if (compare < 0){
1037
//                    instanceStatus = STATUS_NOT_COMPATIBLE;
1038
//                    message = MESG_UPDATE_SCHEMA_VERSION;
1039
//                    available = true;
1040
//                    connect = LABEL_UPDATE_SCHEMA_VERSION;
1041
//                    color = BTN_COLOR_ATTENTION;
1042
//                }else{
1043
//                    available = true;
1044
//                    instanceStatus = STATUS_AVAILABLE;
1045
//                }
1046
//            } catch (CdmSourceException e) {
1047
//                available = false;
1048
//            }
1049
//        }
1050
//
1051
//        setManagedValues(available, instanceStatus, connect, color, schemaVersion);
1052
//        setMessage(message);
1053
//    }
1054
//
1055
//    private void setManagedValues(boolean available, String instanceStatus, String connect, Integer color,
1056
//            String schemaVersion) {
1057
//        Display.getDefault().syncExec(()->{
1058
//            btnConnect.setEnabled(available);
1059
//            btnConnect.setText(connect);
1060
//            Color systemColor = null;
1061
//            if(color != null) {
1062
//                systemColor = Display.getCurrent().getSystemColor(color);
1063
//            }
1064
//            btnConnect.setBackground(systemColor);
1065
//            btnConnect.requestLayout();
1066
//            txtCdmInstanceStatus.setText(instanceStatus);
1067
//            txtServerSchemaVersion.setText(schemaVersion);
1068
//            lblDefaultLogin.setVisible(true);
1069
//         });
1070
//    }
1071

    
1072
    public void connect() {
1073
        checkSelectedCdmInstance();
1074

    
1075
        if(!txtCdmInstanceStatus.getText().equals(STATUS_AVAILABLE)) {
1076
            return;
1077
        }
1078

    
1079
        ICdmRemoteSource source = selectedServerInfo.getCdmRemoteSource(selectedCdmInstance, getPort());
1080

    
1081
        if(!validateLogin(source)) {
1082
            return;
1083
        }
1084

    
1085
        try {
1086
            CdmStore.connect(source, this);
1087
        } catch (Exception e) {
1088
            // Do not expect anything to go wrong at this point, so we throw a runtime exception
1089
            // if any problems
1090
            throw new RuntimeException(e);
1091
        }
1092
    }
1093

    
1094
    public boolean isRememberMe() {
1095
        return btnRememberMe.getSelection();
1096
    }
1097

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

    
1102
        lastServerInstancePrefs.put(LAST_SERVER_KEY, selectedServerInfo.getName());
1103
        lastServerInstancePrefs.put(LAST_INSTANCE_KEY, selectedCdmInstance.getName());
1104

    
1105
        flushPreferences(lastServerInstancePrefs);
1106
    }
1107

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

    
1116
    private void removePrefCredentials() {
1117
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1118
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1119
        credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
1120
        credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
1121
        removePreferences(credentialsPrefs);
1122
    }
1123

    
1124
    private void removePreferences(Preferences prefs) {
1125
        try {
1126
            prefs.removeNode();
1127
        } catch (BackingStoreException bse) {
1128
            setMessage(bse.getMessage());
1129
        }
1130
    }
1131

    
1132
    private void flushPreferences(Preferences prefs) {
1133
        try {
1134
            prefs.flush();
1135
        } catch (BackingStoreException bse) {
1136
            setMessage(bse.getMessage());
1137
        }
1138
    }
1139

    
1140
    protected void readPrefCredentials() {
1141
        String username, password;
1142
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1143
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1144
        username = credentialsPrefs.get(getUsernamePrefKey(), ""); //$NON-NLS-1$
1145
        txtLogin.setText(username);
1146
        password = credentialsPrefs.get(getPasswordPrefKey(),""); //$NON-NLS-1$
1147
        txtPassword.setText(password);
1148
        if(username.isEmpty() || password.isEmpty()) {
1149
            setAutoConnect(false);
1150
        }
1151
    }
1152

    
1153
    private void readPrefLastServerInstance() {
1154
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1155
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
1156

    
1157
        setServerName(lastServerInstancePrefs.get(LAST_SERVER_KEY, null));
1158
        setInstanceName(lastServerInstancePrefs.get(LAST_INSTANCE_KEY, null));
1159
    }
1160

    
1161
    private void emptyCredentials() {
1162
        txtLogin.setText(""); //$NON-NLS-1$
1163
        txtPassword.setText(""); //$NON-NLS-1$
1164
    }
1165

    
1166
    private String getUsernamePrefKey() {
1167
        return selectedServerInfo.toString(selectedCdmInstance.getName(), isDevRemoteSource()?getPort():-1) + USERNAME_SUFFIX;
1168
    }
1169

    
1170
    private String getPasswordPrefKey() {
1171
        return selectedServerInfo.toString(selectedCdmInstance.getName(), isDevRemoteSource()?getPort():-1) + PASSWORD_SUFFIX;
1172
    }
1173

    
1174
    private boolean validateLogin(ICdmRemoteSource remoteSource) {
1175
        if(getUsername() == null || getUsername().isEmpty()) {
1176
            setMessage(Messages.RemotingLoginDialog_LOGIN_CANNOT_BE_EMPTY);
1177
            return false;
1178
        }
1179
        if(getPassword() == null || getPassword().isEmpty()) {
1180
            setMessage(Messages.RemotingLoginDialog_PASSWORD_CANNOT_BE_EMPTY);
1181
            return false;
1182
        }
1183

    
1184
        try {
1185
            IUserService userService = CdmApplicationRemoteConfiguration.getUserService(remoteSource);
1186
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(getUsername(), getPassword());
1187
            CdmApplicationRemoteConfiguration.getAuthenticationManager(userService).authenticate(token);
1188
        } catch(BadCredentialsException e){
1189
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1190
            return false;
1191
        } catch(LockedException e){
1192
            setMessage(LoginManager.ACCOUNT_LOCKED_MESSAGE);
1193
            return false;
1194
        } catch(IllegalArgumentException e){
1195
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1196
            return false;
1197
        }
1198
        return true;
1199
    }
1200

    
1201
    public String getUsername() {
1202
        return txtLogin.getText();
1203
    }
1204

    
1205
    public String getPassword() {
1206
        return txtPassword.getText();
1207
    }
1208

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

    
1235
//    private int getHeightWithoutMessage() {
1236
//        if(xpndblcmpstAdvanced.isExpanded()) {
1237
//            return MIN_EXP_HEIGHT;
1238
//        } else {
1239
//            return MIN_HEIGHT;
1240
//        }
1241
//    }
1242

    
1243
    public void hide(boolean isHidden) {
1244
        if (!shlConnect.isDisposed()){
1245
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1246
                shlConnect.setVisible(!isHidden);
1247
            }
1248
        }
1249
    }
1250

    
1251
    public void dispose() {
1252
        if (!shlConnect.isDisposed()){
1253
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1254
                shlConnect.dispose();
1255
            }
1256
        }
1257
    }
1258

    
1259
    public void onComplete() {
1260
        Display.getDefault().asyncExec(new Runnable() {
1261
            @Override
1262
            public void run() {
1263
                if(selectedCdmInstance!=null){
1264
                    if(isRememberMe()) {
1265
                        persistPrefCredentials();
1266
                    }else{
1267
                        removePrefCredentials();
1268
                    }
1269
                    persistPrefLastServerInstance();
1270
                }
1271
                dispose();
1272
            }
1273
        });
1274
    }
1275

    
1276
    private String generateLastModifiedTooltip(String cdmlibLastModified) {
1277
        if(StringUtils.isBlank(cdmlibLastModified)) {
1278
            return ""; //$NON-NLS-1$
1279
        }
1280
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.z"); //$NON-NLS-1$
1281
        Date cdmlibLastModifiedDate;
1282
        String cdmlibLastModifiedTimestamp = ""; //$NON-NLS-1$
1283

    
1284
        cdmlibLastModifiedDate = new Date(Long.valueOf(cdmlibLastModified));
1285
        cdmlibLastModifiedTimestamp = sdf.format(cdmlibLastModifiedDate);
1286

    
1287
        return cdmlibLastModifiedTimestamp;
1288
    }
1289

    
1290
    private void setEditorInfo() {
1291
        txtEditorCdmVersion.setText(CdmMetaData.getDbSchemaVersion());
1292
        setCdmlibVersion(txtEditorCdmlibVersion);
1293
    }
1294

    
1295
    private void setCdmlibVersion(Text txt) {
1296
        String editorVersionTimestamp = generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified());
1297
        txt.setText(CdmApplicationState.getCdmlibVersion() + ":" + editorVersionTimestamp); //$NON-NLS-1$
1298
    }
1299

    
1300
    private void clearOnServerChange() {
1301
        setMessage(""); //$NON-NLS-1$
1302
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1303
        txtServerCdmlibVersion.setText(""); //$NON-NLS-1$
1304
        txtServerCdmlibVersion.setToolTipText(""); //$NON-NLS-1$
1305
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1306
        comboCdmInstance.removeAll();
1307
        txtCdmInstanceStatus.setText(""); //$NON-NLS-1$
1308
        txtPort.setEditable(false);
1309
        txtPort.setEnabled(false);
1310
    }
1311

    
1312
    private void clearOnInstanceChange() {
1313
        setMessage(""); //$NON-NLS-1$
1314
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1315
        btnConnect.setText(LABEL_CONNECT);
1316
        btnConnect.setBackground(null);
1317
        btnConnect.requestLayout();
1318
    }
1319

    
1320
    @SuppressWarnings("unused")  //in work, for future centralized handling of control's status
1321
    private void updateControls(){
1322

    
1323
        //server
1324
//      comboCdmServer; //nothing to change
1325
        String strServerStatus = this.selectedServerInfo != null? STATUS_NOT_AVAILABLE : STATUS_AVAILABLE;
1326
        txtCdmServerStatus.setText(strServerStatus);
1327
//      btnCdmServerRefresh;  //nothing to change
1328

    
1329
        //database
1330
//        comboCdmInstance
1331
        String strInstanceStatus = this.selectedCdmInstance != null? STATUS_NOT_AVAILABLE : STATUS_AVAILABLE;
1332
        txtCdmInstanceStatus.setText(strInstanceStatus);
1333
//        btnCdmInstanceRefresh;  //nothing to change
1334

    
1335
        //login + connect
1336
        txtLogin.setText(Nz(login));
1337
        txtPassword.setText(Nz(password));
1338
        btnConnect.setText(LABEL_CONNECT);  //TODO
1339
        btnConnect.setEnabled(true);
1340

    
1341
        //rememberMe + defaultValues
1342
//        btnRememberMe;
1343
//        lblDefaultLogin;
1344

    
1345
        //message
1346
//        styledTxtMessage;
1347

    
1348
        //Advanced
1349
//        txtPort
1350
//        btnStopServer;
1351

    
1352
//        txtServerCdmlibVersion;
1353
//        txtEditorCdmlibVersion;
1354
//        txtServerSchemaVersion;
1355
//        txtEditorCdmVersion;
1356
    }
1357

    
1358
    private String Nz(String value) {
1359
        return CdmUtils.Nz(value);
1360
    }
1361

    
1362
    public Map<String, CdmServerInfo> getServerInfoMap() {
1363
        return serverInfoMap;
1364
    }
1365

    
1366
    public String getServerName() {
1367
        return serverName;
1368
    }
1369

    
1370
    public void setServerName(String serverName) {
1371
        this.serverName = serverName;
1372
    }
1373

    
1374
    public boolean isAutoConnect() {
1375
        return autoConnect;
1376
    }
1377

    
1378
    public void setAutoConnect(boolean autoConnect) {
1379
        this.autoConnect = autoConnect;
1380
    }
1381

    
1382
    public boolean isDevRemoteSource() {
1383
        return isDevRemoteSource;
1384
    }
1385

    
1386
    public void setDevRemoteSource(boolean isDevRemoteSource) {
1387
        this.isDevRemoteSource = isDevRemoteSource;
1388
    }
1389

    
1390
    public String getInstanceName() {
1391
        return instanceName;
1392
    }
1393

    
1394
    public void setInstanceName(String instanceName) {
1395
        this.instanceName = instanceName;
1396
    }
1397

    
1398
    @Override
1399
    public void handleError(Throwable t) {
1400
        Display.getDefault().syncExec(()-> {
1401
            serverJob.cancel();
1402

    
1403
            String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
1404
            String  message = t.getMessage();
1405

    
1406
            MessagingUtils.errorDialog(title,
1407
                    this,
1408
                    message,
1409
                    TaxeditorStorePlugin.PLUGIN_ID,
1410
                    t,
1411
                    true);
1412
        });
1413

    
1414
    }
1415
}
(5-5/8)