Project

General

Profile

Download (58.9 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.logging.log4j.LogManager;import org.apache.logging.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 = LogManager.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
    @SuppressWarnings("unused")
517
    private void addEmptyCells(int cnt) {
518
        for (int i = 0; i < cnt; i++) {
519
            new Label(compAdvanced, SWT.NONE);
520
        }
521
    }
522

    
523
	protected void onConnectButtonPressed() {
524
		/*if(selectedServerInfo.isLocalhostMgd() && !isSelectedCdmInstanceRunningInManagedServer()) {
525
			startManagedServer();
526
		} else {*/
527
			connect();
528
			if (CdmStore.isActive() && CdmStore.currentAuthentiationHasOneOfRoles(Role.ROLE_REMOTING)){
529
			    PreferencesUtil.setNomenclaturalCodePreferences();
530
			}
531
//		}
532
	}
533

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

    
568

    
569
                });
570
                return Status.OK_STATUS;
571
            }
572
        };
573
        job.schedule();
574
    }
575
    public void putAllServers() {
576
        for(CdmServerInfo csii : CdmServerInfo.getCdmServers(isLocal)) {
577
            putServerInfo(csii);
578
            comboCdmServer.add(csii.getName());
579
        }
580
    }
581

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

    
604
    protected void updateSelectedCdmServer() {
605
        int selIndex = comboCdmServer.getSelectionIndex();
606
        if(selIndex != -1) {
607
            selectedServerInfo = getServerInfoMap().get(comboCdmServer.getItem(selIndex));
608
        }
609
    }
610

    
611
    protected void updatePort() {
612
        txtPort.setText(""); //$NON-NLS-1$
613
        if(selectedServerInfo != null) {
614
            int port = selectedServerInfo.getPort();
615
            if(port == CdmServerInfo.NULL_PORT) {
616
                txtPort.setText(CdmServerInfo.NULL_PORT_STRING);
617
            } else {
618
                txtPort.setText(String.valueOf(port));
619
            }
620
        }
621
    }
622

    
623
    protected int getPort() {
624
        int port = CdmServerInfo.NULL_PORT;
625
        try {
626
            port = Integer.valueOf(txtPort.getText());
627
        } catch (NumberFormatException nfe) {
628
            if(!CdmServerInfo.NULL_PORT_STRING.equals(txtPort.getText())) {
629
                setMessage(Messages.RemotingLoginDialog_MESSAGE_PORT_SHOULD_BE_INTEGER);
630
            }
631
        }
632
        return port;
633
    }
634

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

    
681
    protected void populateCdmInstanceCombo(final boolean forceRefresh) {
682
        comboCdmInstance.removeAll();
683
        comboCdmInstance.setEnabled(false);
684
        btnConnect.setEnabled(false);
685
        txtCdmInstanceStatus.setText(STATUS_RETRIEVING);
686
        txtCdmInstanceStatus.setToolTipText(""); //$NON-NLS-1$
687

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

    
736
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE) && !isDevRemoteSource()) {
737
            // Start the Job
738
            serverJob.schedule();
739
        }
740
    }
741

    
742
    public void disableCdmInstanceControls(String cdmInstanceStatus, String tooltip) {
743
        txtCdmInstanceStatus.setText(cdmInstanceStatus);
744
        txtCdmInstanceStatus.setToolTipText(tooltip);
745
        comboCdmInstance.setEnabled(false);
746
        btnConnect.setEnabled(false);
747
    }
748

    
749
    public void onRefreshCdmInstance() {
750
        txtCdmInstanceStatus.setText(STATUS_CHECKING_AVAILABILITY);
751
        clearOnInstanceChange();
752
        updateSelectedCdmInstance();
753
        checkSelectedCdmInstance();
754
//        updateManagedServerControls();
755
    }
756

    
757
    protected void updateSelectedCdmInstance() {
758
        int selIndex = comboCdmInstance.getSelectionIndex();
759
        if(selIndex != -1) {
760
            selectedCdmInstance = selectedServerInfo.getInstanceFromName(comboCdmInstance.getItem(selIndex));
761
            if(loadLoginPrefs) {
762
                readPrefCredentials();
763
            }
764
        }
765
    }
766
/*
767
    private void updateManagedServerControls() {
768
        if(selectedServerInfo.isLocalhostMgd()) {
769
            if(isSelectedCdmInstanceRunningInManagedServer()) {
770
                txtCdmInstanceStatus.setText(STATUS_STARTED);
771
            } else {
772
                txtCdmInstanceStatus.setText(STATUS_NOT_STARTED);
773
            }
774
            btnConnect.setEnabled(true);
775
            selectedServerInfo.setPort(getManagedServerPort());
776
            updatePort();
777
        }
778

    
779
        if(isManagedServerRunning()) {
780
            btnStopServer.setEnabled(true);
781
        } else {
782
            btnStopServer.setEnabled(false);
783
        }
784
    }
785

    
786
    private boolean isManagedServerRunning() {
787
        return CdmStore.getManagedServer() != null && CdmStore.getManagedServer().isAlive();
788
    }
789

    
790
    private boolean isSelectedCdmInstanceRunningInManagedServer() {
791
        return CdmStore.getManagedServer() != null &&
792
                CdmStore.getManagedServer().isAlive() &&
793
                selectedServerInfo.isLocalhostMgd() &&
794
                CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName());
795
    }
796

    
797
    private void startManagedServer() {
798
        /*if(isManagedServerRunning()) {
799
            if(CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())) {
800
                return;
801
            } else {
802
                Display.getDefault().syncExec(new Runnable() {
803
                    @Override
804
                    public void run() {
805
                        onStopManagedServer();
806
                    }
807
                });
808
            }
809
        }
810
        boolean forceSchemaCreate = !schemaExists(selectedCdmInstance);
811
        boolean forceSchemaUpdate = LABEL_UPDATE_SCHEMA_VERSION.equals(btnConnect.getText());
812

    
813
        Job job = new Job(Messages.RemotingLoginDialog_JOB_SERVER_LAUNCH) {
814

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

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

    
870
                return Status.OK_STATUS;
871
            }
872
       };
873

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

    
896
    private String managedSchemaVersion(CdmInstanceInfo instanceInfo) throws CdmSourceException{
897
        if (instanceInfo.getDataSource() != null){
898
            return instanceInfo.getDataSource().getDbSchemaVersion();
899
        }else{
900
            throw new RuntimeException("ManagedSchemaVersion only available for managed server instances.");
901
        }
902
    }
903
    private int compareSchemaVersion(CdmInstanceInfo instanceInfo) throws CdmSourceException {
904
        return CdmMetaData.compareVersion(managedSchemaVersion(instanceInfo), CdmMetaData.getDbSchemaVersion(), 3, null);
905
    }
906
/*
907
    @Override
908
    public void handleError(final Throwable t) {
909

    
910
        Display.getDefault().syncExec(()-> {
911
            serverJob.cancel();
912

    
913
            String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
914
            String  message = t.getMessage();
915

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

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

    
940
    private int getManagedServerPort() {
941
        return CdmStore.getManagedServer() == null ? CdmServerInfo.NULL_PORT : CdmStore.getManagedServer().getPort();
942
    }
943
*/
944
    protected void checkSelectedCdmInstance() {
945
        try {
946
            if (selectedCdmInstance != null && selectedCdmInstance.getDataSource() != null){
947
                String schemaVersion = selectedCdmInstance.getDataSource().getDbSchemaVersion();
948
            }
949
        } catch (CdmSourceException e1) {
950
            // TODO Auto-generated catch block
951
            e1.printStackTrace();
952
        }
953
       if (txtCdmServerStatus.getText().equals(STATUS_AVAILABLE)) {
954

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

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

    
970
                    int compareDbSchemaVersion = selectedServerInfo.compareDbSchemaVersion(selectedCdmInstance, getPort());
971

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

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

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

    
1064
    public void connect() {
1065
        checkSelectedCdmInstance();
1066

    
1067
        if(!txtCdmInstanceStatus.getText().equals(STATUS_AVAILABLE)) {
1068
            return;
1069
        }
1070

    
1071
        ICdmRemoteSource source = selectedServerInfo.getCdmRemoteSource(selectedCdmInstance, getPort());
1072

    
1073
        if(!validateLogin(source)) {
1074
            return;
1075
        }
1076

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

    
1086
    public boolean isRememberMe() {
1087
        return btnRememberMe.getSelection();
1088
    }
1089

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

    
1094
        lastServerInstancePrefs.put(LAST_SERVER_KEY, selectedServerInfo.getName());
1095
        lastServerInstancePrefs.put(LAST_INSTANCE_KEY, selectedCdmInstance.getName());
1096

    
1097
        flushPreferences(lastServerInstancePrefs);
1098
    }
1099

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

    
1108
    private void removePrefCredentials() {
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
        removePreferences(credentialsPrefs);
1114
    }
1115

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

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

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

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

    
1149
        setServerName(lastServerInstancePrefs.get(LAST_SERVER_KEY, null));
1150
        setInstanceName(lastServerInstancePrefs.get(LAST_INSTANCE_KEY, null));
1151
    }
1152

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

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

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

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

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

    
1193
    public String getUsername() {
1194
        return txtLogin.getText();
1195
    }
1196

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

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

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

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

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

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

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

    
1276
        cdmlibLastModifiedDate = new Date(Long.valueOf(cdmlibLastModified));
1277
        cdmlibLastModifiedTimestamp = sdf.format(cdmlibLastModifiedDate);
1278

    
1279
        return cdmlibLastModifiedTimestamp;
1280
    }
1281

    
1282
    private void setEditorInfo() {
1283
        txtEditorCdmVersion.setText(CdmMetaData.getDbSchemaVersion());
1284
        setCdmlibVersion(txtEditorCdmlibVersion);
1285
    }
1286

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

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

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

    
1312
    @SuppressWarnings("unused")  //in work, for future centralized handling of control's status
1313
    private void updateControls(){
1314

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

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

    
1327
        //login + connect
1328
        txtLogin.setText(Nz(login));
1329
        txtPassword.setText(Nz(password));
1330
        btnConnect.setText(LABEL_CONNECT);  //TODO
1331
        btnConnect.setEnabled(true);
1332

    
1333
        //rememberMe + defaultValues
1334
//        btnRememberMe;
1335
//        lblDefaultLogin;
1336

    
1337
        //message
1338
//        styledTxtMessage;
1339

    
1340
        //Advanced
1341
//        txtPort
1342
//        btnStopServer;
1343

    
1344
//        txtServerCdmlibVersion;
1345
//        txtEditorCdmlibVersion;
1346
//        txtServerSchemaVersion;
1347
//        txtEditorCdmVersion;
1348
    }
1349

    
1350
    private String Nz(String value) {
1351
        return CdmUtils.Nz(value);
1352
    }
1353

    
1354
    public Map<String, CdmServerInfo> getServerInfoMap() {
1355
        return serverInfoMap;
1356
    }
1357

    
1358
    public String getServerName() {
1359
        return serverName;
1360
    }
1361

    
1362
    public void setServerName(String serverName) {
1363
        this.serverName = serverName;
1364
    }
1365

    
1366
    public boolean isAutoConnect() {
1367
        return autoConnect;
1368
    }
1369

    
1370
    public void setAutoConnect(boolean autoConnect) {
1371
        this.autoConnect = autoConnect;
1372
    }
1373

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

    
1378
    public void setDevRemoteSource(boolean isDevRemoteSource) {
1379
        this.isDevRemoteSource = isDevRemoteSource;
1380
    }
1381

    
1382
    public String getInstanceName() {
1383
        return instanceName;
1384
    }
1385

    
1386
    public void setInstanceName(String instanceName) {
1387
        this.instanceName = instanceName;
1388
    }
1389

    
1390
    @Override
1391
    public void handleError(Throwable t) {
1392
        Display.getDefault().syncExec(()-> {
1393
            serverJob.cancel();
1394

    
1395
            String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
1396
            String  message = t.getMessage();
1397

    
1398
            MessagingUtils.errorDialog(title,
1399
                    this,
1400
                    message,
1401
                    TaxeditorStorePlugin.PLUGIN_ID,
1402
                    t,
1403
                    true);
1404
        });
1405

    
1406
    }
1407
}
(5-5/8)