Project

General

Profile

Download (59.2 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
import eu.etaxonomy.taxeditor.webapp.CdmEmbeddedServerException;
81
import eu.etaxonomy.taxeditor.webapp.CdmServer;
82
import eu.etaxonomy.taxeditor.webapp.ICDMServerError;
83
*/
84
/**
85
 * @author cmathew
86
 * @date 20 Jan 2015
87
 */
88
public class RemotingLoginDialog extends Dialog implements ICdmServerError {
89

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

    
92
    public static final String DEFAULT_PASS = "00000"; //$NON-NLS-1$
93
    public static final String DEFAULT_USER = "admin"; //$NON-NLS-1$
94

    
95
    public final static String STATUS_AVAILABLE = Messages.RemotingLoginDialog_STATUS_AVAILABLE;
96
    public final static String STATUS_NOT_AVAILABLE = Messages.RemotingLoginDialog_STATUS_NOT_AVAILABLE;
97
    public final static String STATUS_STARTED = Messages.RemotingLoginDialog_STATUS_STARTED;
98
    public final static String STATUS_NOT_STARTED = Messages.RemotingLoginDialog_STATUS_NOT_STARTED;
99
    public final static String STATUS_RETRIEVING = Messages.RemotingLoginDialog_STATUS_RETRIEVING;
100
    public final static String STATUS_CHECKING_AVAILABILITY = Messages.RemotingLoginDialog_STATUS_CHECKING;
101
    public final static String STATUS_NO_INSTANCES = Messages.RemotingLoginDialog_STATUS_NO_INSTANCES_FOUND;
102
    public final static String STATUS_NOT_COMPATIBLE = Messages.RemotingLoginDialog_STATUS_NOT_COMPATIBLE;
103

    
104
    public final static String MESG_COMPATIBLE_EDITOR_OLD = Messages.RemotingLoginDialog_UPDATE_EDITOR;
105
    public final static String MESG_COMPATIBLE_SERVER_OLD = Messages.RemotingLoginDialog_CHOOSE_COMPATIBLE_CDM_SERVER;
106
    public final static String MESG_SCHEMA_MISSING = Messages.RemotingLoginDialog_SCHEMA_MISSING;
107
    public final static String MESG_NO_SCHEMA = Messages.RemotingLoginDialog_NO_SCHEMA;
108

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

    
129
    public final static String MESG_LOGIN_CANNOT_BE_EMPTY = Messages.RemotingLoginDialog_LOGIN_CANNOT_BE_EMPTY;
130
    public final static String STATUS_GENERATING_CONFIG_FILE = Messages.RemotingLoginDialog_GENERATING_CONFIG_FILE;
131
    public final static String STATUS_STARTING_MGD_SERVER = Messages.RemotingLoginDialog_STARTING_MGD_SERVER;
132

    
133
    public final static String ERR_GENERATING_CONFIG_FILE = Messages.RemotingLoginDialog_ERROR_GENERATING_CONFIG_FILE;
134
    public final static String ERR_STARTING_SERVER = Messages.RemotingLoginDialog_ERROR_STARTING_SERVER;
135
    public final static String ERR_SERVER_LAUNCH = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
136
    public final static String ERR_STOPPING_SERVER = Messages.RemotingLoginDialog_ERROR_STOPPING_SERVER;
137
    public final static String ERR_COULD_NOT_STOP_SERVER = Messages.RemotingLoginDialog_COULD_NOT_STOP_SERVER;
138
    public final static String RETRIEVE_SERVER_INSTANCES = Messages.RemotingLoginDialog_RETRIEVE_SERVER_INSTANCES;
139
    public final static String TASK_LAUNCHING_SERVER = Messages.RemotingLoginDialog_TASK_LAUNCHING_SERVER;
140

    
141
    public static final int BTN_COLOR_ATTENTION = SWT.COLOR_RED;
142

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

    
145
    public final static String LOGIN_NODE = "login"; //$NON-NLS-1$
146
    public final static String USERNAME_SUFFIX = "_username"; //$NON-NLS-1$
147
    public final static String PASSWORD_SUFFIX = "_password"; //$NON-NLS-1$
148

    
149
    public final static String LAST_SERVER_INSTANCE_NODE = "lastServerInstance"; //$NON-NLS-1$
150
    public final static String LAST_SERVER_KEY = "lastServerKey"; //$NON-NLS-1$
151
    public final static String LAST_INSTANCE_KEY = "lastInstanceKey"; //$NON-NLS-1$
152

    
153
    protected Shell shlConnect;
154
    protected Text txtCdmServerStatus;
155
    protected Text txtCdmInstanceStatus;
156
    protected Combo comboCdmServer;
157
    protected Combo comboCdmInstance;
158
    protected Button btnConnect;
159

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

    
179
    protected Label lblEditorCdmlibVersion;
180
    protected Text txtEditorCdmlibVersion;
181
    protected Label lblServerSchemaVersion;
182
    protected Text txtServerSchemaVersion;
183
    protected Label lblEditorCdmVersion;
184
    protected Text txtEditorCdmVersion;
185

    
186
    protected final int MESSAGE_HEIGHT = 50;
187
    protected final int COMBO_MIN_WIDTH =200;
188
    protected final int CONTROLS_MIN_HEIGHT = 23; //does not seem to work yet
189
//  private final int MIN_EXP_HEIGHT = 380;
190

    
191
    protected boolean autoConnect = false;
192
    protected boolean loadLoginPrefs = true;
193
    protected boolean isDevRemoteSource = false;
194
    protected boolean isLocal = false;
195

    
196
    protected Job serverJob;
197
    protected Object result;
198

    
199
    protected final Map<String, CdmServerInfo> serverInfoMap = new HashMap<>();
200

    
201
    protected String serverName;
202
    protected String instanceName;
203
    protected CdmServerInfo selectedServerInfo;
204
    protected CdmInstanceInfo selectedCdmInstance;
205
    protected String login;
206
    protected String password;
207

    
208
    /**
209
     * Create the dialog.
210
     * @param parent
211
     * @param style
212
     */
213
    public RemotingLoginDialog(Shell parent, int style) {
214
        super(parent, style);
215
        setText(LABEL_LOGIN);
216
    }
217

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

    
230
    public Object open(String serverName, String instanceName, boolean loadLoginPrefs, boolean autoConnect) {
231
        this.setServerName(serverName);
232
        this.setInstanceName(instanceName);
233
        this.loadLoginPrefs = loadLoginPrefs;
234
        this.setAutoConnect(autoConnect);
235
        return open();
236
    }
237

    
238
    /**
239
     * Open the dialog.
240
     * @return the dialog result
241
     */
242
    public Object open() {
243

    
244
        createContents();
245
        if(getServerName() == null && getInstanceName() == null) {
246
            readPrefLastServerInstance();
247
        }
248
        expandableCompositeAdvanced.setExpanded(false);
249

    
250
        setEditorInfo();
251
        populateCdmServerCombo();
252
        shlConnect.pack(true);
253

    
254
        setCenterPoint();
255
        shlConnect.open();
256

    
257
        Display display = getParent().getDisplay();
258
        while (!shlConnect.isDisposed()) {
259
            if (!display.isDisposed()){
260
                if (!display.readAndDispatch()) {
261
                    display.sleep();
262
                }
263
            }
264
        }
265
        return result;
266
    }
267

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

    
276
        remotingComposite = new Composite(shlConnect, SWT.NONE);
277
        remotingComposite.setLayout(new GridLayout(1, false));
278

    
279
        //server
280
        Composite cdmServerComposite = new Composite(remotingComposite, SWT.NONE);
281
        GridData gd_cdmServerComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
282
        cdmServerComposite.setLayoutData(gd_cdmServerComposite);
283
        cdmServerComposite.setLayout(new GridLayout(4, false));
284

    
285
        Label lblCdmServer = new Label(cdmServerComposite, SWT.NONE);
286
        lblCdmServer.setText(LABEL_CDM_SERVER);
287
        lblCdmServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
288

    
289
        comboCdmServer = new Combo(cdmServerComposite, SWT.READ_ONLY);
290
        comboCdmServer.addSelectionListener(new SelectionAdapter() {
291
            @Override
292
            public void widgetSelected(SelectionEvent e) {
293
                onRefreshCdmServer();
294
            }
295
        });
296

    
297
        GridData gd_comboCdmServer = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
298

    
299
        comboCdmServer.setLayoutData(gd_comboCdmServer);
300
        comboCdmServer.select(0);
301

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

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

    
321
        //instance
322
        Label lblCdmInstance = new Label(cdmServerComposite, SWT.NONE);
323
        GridData gd_lblCdmInstance = new GridData(SWT.RIGHT, SWT.CENTER, false, true, 1, 1);
324
        //gd_lblCdmInstance.heightHint = 30;
325
        lblCdmInstance.setLayoutData(gd_lblCdmInstance);
326
        lblCdmInstance.setText(LABEL_CDM_INSTANCE);
327

    
328
        comboCdmInstance = new Combo(cdmServerComposite, SWT.READ_ONLY);
329
        comboCdmInstance.addSelectionListener(new SelectionAdapter() {
330
            @Override
331
            public void widgetSelected(SelectionEvent e) {
332
                onRefreshCdmInstance();
333
            }
334
        });
335

    
336
        GridData gd_comboCdmInstance = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
337
        gd_comboCdmInstance.minimumWidth = COMBO_MIN_WIDTH;
338

    
339
        comboCdmInstance.setLayoutData(gd_comboCdmInstance);
340
        comboCdmInstance.select(0);
341

    
342
        txtCdmInstanceStatus = new Text(cdmServerComposite, SWT.BORDER);
343
        txtCdmInstanceStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
344
        txtCdmInstanceStatus.setEditable(false);
345
        GridData gd_txtCdmInstanceStatus = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
346
        gd_txtCdmInstanceStatus.minimumHeight = CONTROLS_MIN_HEIGHT;
347
        txtCdmInstanceStatus.setLayoutData(gd_txtCdmInstanceStatus);
348

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

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

    
369
        lblLogin = new Label(loginComposite, SWT.CENTER);
370
        GridData gd_lblLogin = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
371
        lblLogin.setLayoutData(gd_lblLogin);
372
        lblLogin.setText(Messages.RemotingLoginDialog_LABEL_LOGIN_COLON);
373

    
374
        txtLogin = new Text(loginComposite, SWT.BORDER);
375
        GridData gd_txtLogin = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
376
        gd_txtLogin.minimumWidth = 80;
377
        txtLogin.setLayoutData(gd_txtLogin);
378

    
379
        lblPassword = new Label(loginComposite, SWT.CENTER);
380
        lblPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
381
        lblPassword.setText(Messages.RemotingLoginDialog_LABEL_PASSWORD);
382

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

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

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

    
417
        lblDefaultLogin = new Label(loginComposite, SWT.NONE);
418
        GridDataFactory.fillDefaults().span(4, 1).align(SWT.TRAIL, SWT.CENTER).applyTo(lblDefaultLogin);
419
        lblDefaultLogin.setText(String.format(Messages.RemotingLoginDialog_DEFAULT_LOGIN, DEFAULT_USER, DEFAULT_PASS));
420
        lblDefaultLogin.setVisible(false);
421

    
422
        styledTxtMessage = new StyledText(remotingComposite, SWT.NONE);
423
        styledTxtMessage.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
424
        styledTxtMessage.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
425
        styledTxtMessage.setSelectionBackground(SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION_TEXT));
426
        styledTxtMessage.setSelectionForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
427
        styledTxtMessage.setDoubleClickEnabled(false);
428
        styledTxtMessage.setEditable(false);
429
        styledTxtMessage.setWordWrap(true);
430

    
431
        GridData gd_styledTxtMessage = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
432
        gd_styledTxtMessage.exclude = true;
433
        gd_styledTxtMessage.minimumHeight = MESSAGE_HEIGHT;
434

    
435
        styledTxtMessage.setLayoutData(gd_styledTxtMessage);
436

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

    
453
        compAdvanced = new Composite(expandableCompositeAdvanced, SWT.NONE);
454
        expandableCompositeAdvanced.setClient(compAdvanced);
455
        compAdvanced.setLayout(new GridLayout(4, false));
456

    
457
        lblPort = new Label(compAdvanced, SWT.CENTER);
458
        lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
459
        lblPort.setText(Messages.RemotingLoginDialog_LABEL_PORT);
460

    
461
        txtPort = new Text(compAdvanced, SWT.BORDER);
462
        GridData gd_txtPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
463
        gd_txtPort.minimumWidth = 50;
464
        txtPort.setLayoutData(gd_txtPort);
465

    
466
        lblServerCdmlibVersion = new Label(compAdvanced, SWT.CENTER);
467
        lblServerCdmlibVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
468
        lblServerCdmlibVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDMLIB_VERSION);
469

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

    
488
        txtEditorCdmlibVersion = new Text(compAdvanced, SWT.BORDER);
489
        txtEditorCdmlibVersion.setEditable(false);
490
        txtEditorCdmlibVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
491
        addEmptyCells(2);
492

    
493
        lblServerSchemaVersion = new Label(compAdvanced, SWT.CENTER);
494
        lblServerSchemaVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
495
        lblServerSchemaVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDM_VERSION);
496

    
497
        txtServerSchemaVersion = new Text(compAdvanced, SWT.BORDER);
498
        txtServerSchemaVersion.setEditable(false);
499
        txtServerSchemaVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
500
        addEmptyCells(2);
501

    
502
        lblEditorCdmVersion = new Label(compAdvanced, SWT.CENTER);
503
        lblEditorCdmVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
504
        lblEditorCdmVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDM_VERSION);
505

    
506
        txtEditorCdmVersion = new Text(compAdvanced, SWT.BORDER);
507
        txtEditorCdmVersion.setEditable(false);
508
        txtEditorCdmVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
509
    }
510

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

    
518
    }
519

    
520

    
521

    
522

    
523

    
524

    
525
    @SuppressWarnings("unused")
526
    private void addEmptyCells(int cnt) {
527
        for (int i = 0; i < cnt; i++) {
528
            new Label(compAdvanced, SWT.NONE);
529
        }
530
    }
531

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

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

    
577

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

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

    
613
    protected void updateSelectedCdmServer() {
614
        int selIndex = comboCdmServer.getSelectionIndex();
615
        if(selIndex != -1) {
616
            selectedServerInfo = getServerInfoMap().get(comboCdmServer.getItem(selIndex));
617
        }
618
    }
619

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

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

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

    
690
    protected void populateCdmInstanceCombo(final boolean forceRefresh) {
691
        comboCdmInstance.removeAll();
692
        comboCdmInstance.setEnabled(false);
693
        btnConnect.setEnabled(false);
694
        txtCdmInstanceStatus.setText(STATUS_RETRIEVING);
695
        txtCdmInstanceStatus.setToolTipText(""); //$NON-NLS-1$
696

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

    
748
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE) && !isDevRemoteSource()) {
749
            // Start the Job
750
            serverJob.schedule();
751
        }
752
    }
753

    
754
    public void disableCdmInstanceControls(String cdmInstanceStatus, String tooltip) {
755
        txtCdmInstanceStatus.setText(cdmInstanceStatus);
756
        txtCdmInstanceStatus.setToolTipText(tooltip);
757
        comboCdmInstance.setEnabled(false);
758
        btnConnect.setEnabled(false);
759
    }
760

    
761
    public void onRefreshCdmInstance() {
762
        txtCdmInstanceStatus.setText(STATUS_CHECKING_AVAILABILITY);
763
        clearOnInstanceChange();
764
        updateSelectedCdmInstance();
765
        checkSelectedCdmInstance();
766
//        updateManagedServerControls();
767
    }
768

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

    
791
        if(isManagedServerRunning()) {
792
            btnStopServer.setEnabled(true);
793
        } else {
794
            btnStopServer.setEnabled(false);
795
        }
796
    }
797

    
798
    private boolean isManagedServerRunning() {
799
        return CdmStore.getManagedServer() != null && CdmStore.getManagedServer().isAlive();
800
    }
801

    
802
    private boolean isSelectedCdmInstanceRunningInManagedServer() {
803
        return CdmStore.getManagedServer() != null &&
804
                CdmStore.getManagedServer().isAlive() &&
805
                selectedServerInfo.isLocalhostMgd() &&
806
                CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName());
807
    }
808

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

    
825
        Job job = new Job(Messages.RemotingLoginDialog_JOB_SERVER_LAUNCH) {
826

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

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

    
882
                return Status.OK_STATUS;
883
            }
884
       };
885

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

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

    
922
        Display.getDefault().syncExec(()-> {
923
            serverJob.cancel();
924

    
925
            String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
926
            String  message = t.getMessage();
927

    
928
            MessagingUtils.errorDialog(title,
929
                    this,
930
                    message,
931
                    TaxeditorStorePlugin.PLUGIN_ID,
932
                    t,
933
                    true);
934
        });
935
    }
936

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

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

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

    
979
                if(available) {
980
                    txtServerSchemaVersion.setText(selectedServerInfo.getCdmRemoteSource(selectedCdmInstance, getPort()).getDbSchemaVersion());
981

    
982
                    int compareDbSchemaVersion = selectedServerInfo.compareDbSchemaVersion(selectedCdmInstance, getPort());
983

    
984
                    int compareCdmlibServicesVersion = 0;
985
                    boolean disableServicesApiTimestampCheck =
986
                            PreferencesUtil.getBooleanValue((IPreferenceKeys.DISABLE_SERVICES_API_TIMESTAMP_CHECK));
987
                    if(!disableServicesApiTimestampCheck) {
988
                        compareCdmlibServicesVersion = selectedServerInfo.compareCdmlibServicesVersion();
989
                    }
990

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

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

    
1076
    public void connect() {
1077
        checkSelectedCdmInstance();
1078

    
1079
        if(!txtCdmInstanceStatus.getText().equals(STATUS_AVAILABLE)) {
1080
            return;
1081
        }
1082

    
1083
        ICdmRemoteSource source = selectedServerInfo.getCdmRemoteSource(selectedCdmInstance, getPort());
1084

    
1085
        if(!validateLogin(source)) {
1086
            return;
1087
        }
1088

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

    
1098
    public boolean isRememberMe() {
1099
        return btnRememberMe.getSelection();
1100
    }
1101

    
1102
    private void persistPrefLastServerInstance() {
1103
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1104
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
1105

    
1106
        lastServerInstancePrefs.put(LAST_SERVER_KEY, selectedServerInfo.getName());
1107
        lastServerInstancePrefs.put(LAST_INSTANCE_KEY, selectedCdmInstance.getName());
1108

    
1109
        flushPreferences(lastServerInstancePrefs);
1110
    }
1111

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

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

    
1128
    private void removePreferences(Preferences prefs) {
1129
        try {
1130
            prefs.removeNode();
1131
        } catch (BackingStoreException bse) {
1132
            setMessage(bse.getMessage());
1133
        }
1134
    }
1135

    
1136
    private void flushPreferences(Preferences prefs) {
1137
        try {
1138
            prefs.flush();
1139
        } catch (BackingStoreException bse) {
1140
            setMessage(bse.getMessage());
1141
        }
1142
    }
1143

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

    
1157
    private void readPrefLastServerInstance() {
1158
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1159
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
1160

    
1161
        setServerName(lastServerInstancePrefs.get(LAST_SERVER_KEY, null));
1162
        setInstanceName(lastServerInstancePrefs.get(LAST_INSTANCE_KEY, null));
1163
    }
1164

    
1165
    private void emptyCredentials() {
1166
        txtLogin.setText(""); //$NON-NLS-1$
1167
        txtPassword.setText(""); //$NON-NLS-1$
1168
    }
1169

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

    
1174
    private String getPasswordPrefKey() {
1175
        return selectedServerInfo.toString(selectedCdmInstance.getName(), isDevRemoteSource()?getPort():-1) + PASSWORD_SUFFIX;
1176
    }
1177

    
1178
    private boolean validateLogin(ICdmRemoteSource remoteSource) {
1179
        if(getUsername() == null || getUsername().isEmpty()) {
1180
            setMessage(Messages.RemotingLoginDialog_LOGIN_CANNOT_BE_EMPTY);
1181
            return false;
1182
        }
1183
        if(getPassword() == null || getPassword().isEmpty()) {
1184
            setMessage(Messages.RemotingLoginDialog_PASSWORD_CANNOT_BE_EMPTY);
1185
            return false;
1186
        }
1187

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

    
1205
    public String getUsername() {
1206
        return txtLogin.getText();
1207
    }
1208

    
1209
    public String getPassword() {
1210
        return txtPassword.getText();
1211
    }
1212

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

    
1239
//    private int getHeightWithoutMessage() {
1240
//        if(xpndblcmpstAdvanced.isExpanded()) {
1241
//            return MIN_EXP_HEIGHT;
1242
//        } else {
1243
//            return MIN_HEIGHT;
1244
//        }
1245
//    }
1246

    
1247
    public void hide(boolean isHidden) {
1248
        if (!shlConnect.isDisposed()){
1249
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1250
                shlConnect.setVisible(!isHidden);
1251
            }
1252
        }
1253
    }
1254

    
1255
    public void dispose() {
1256
        if (!shlConnect.isDisposed()){
1257
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1258
                shlConnect.dispose();
1259
            }
1260
        }
1261
    }
1262

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

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

    
1288
        cdmlibLastModifiedDate = new Date(Long.valueOf(cdmlibLastModified));
1289
        cdmlibLastModifiedTimestamp = sdf.format(cdmlibLastModifiedDate);
1290

    
1291
        return cdmlibLastModifiedTimestamp;
1292
    }
1293

    
1294
    private void setEditorInfo() {
1295
        txtEditorCdmVersion.setText(CdmMetaData.getDbSchemaVersion());
1296
        setCdmlibVersion(txtEditorCdmlibVersion);
1297
    }
1298

    
1299
    private void setCdmlibVersion(Text txt) {
1300
        String editorVersionTimestamp = generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified());
1301
        txt.setText(CdmApplicationState.getCdmlibVersion() + ":" + editorVersionTimestamp); //$NON-NLS-1$
1302
    }
1303

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

    
1316
    private void clearOnInstanceChange() {
1317
        setMessage(""); //$NON-NLS-1$
1318
        txtServerSchemaVersion.setText(""); //$NON-NLS-1$
1319
        btnConnect.setText(LABEL_CONNECT);
1320
        btnConnect.setBackground(null);
1321
        btnConnect.requestLayout();
1322
    }
1323

    
1324
    @SuppressWarnings("unused")  //in work, for future centralized handling of control's status
1325
    private void updateControls(){
1326

    
1327
        //server
1328
//      comboCdmServer; //nothing to change
1329
        String strServerStatus = this.selectedServerInfo != null? STATUS_NOT_AVAILABLE : STATUS_AVAILABLE;
1330
        txtCdmServerStatus.setText(strServerStatus);
1331
//      btnCdmServerRefresh;  //nothing to change
1332

    
1333
        //database
1334
//        comboCdmInstance
1335
        String strInstanceStatus = this.selectedCdmInstance != null? STATUS_NOT_AVAILABLE : STATUS_AVAILABLE;
1336
        txtCdmInstanceStatus.setText(strInstanceStatus);
1337
//        btnCdmInstanceRefresh;  //nothing to change
1338

    
1339
        //login + connect
1340
        txtLogin.setText(Nz(login));
1341
        txtPassword.setText(Nz(password));
1342
        btnConnect.setText(LABEL_CONNECT);  //TODO
1343
        btnConnect.setEnabled(true);
1344

    
1345
        //rememberMe + defaultValues
1346
//        btnRememberMe;
1347
//        lblDefaultLogin;
1348

    
1349
        //message
1350
//        styledTxtMessage;
1351

    
1352
        //Advanced
1353
//        txtPort
1354
//        btnStopServer;
1355

    
1356
//        txtServerCdmlibVersion;
1357
//        txtEditorCdmlibVersion;
1358
//        txtServerSchemaVersion;
1359
//        txtEditorCdmVersion;
1360
    }
1361

    
1362
    private String Nz(String value) {
1363
        return CdmUtils.Nz(value);
1364
    }
1365

    
1366
    public Map<String, CdmServerInfo> getServerInfoMap() {
1367
        return serverInfoMap;
1368
    }
1369

    
1370
    public String getServerName() {
1371
        return serverName;
1372
    }
1373

    
1374
    public void setServerName(String serverName) {
1375
        this.serverName = serverName;
1376
    }
1377

    
1378
    public boolean isAutoConnect() {
1379
        return autoConnect;
1380
    }
1381

    
1382
    public void setAutoConnect(boolean autoConnect) {
1383
        this.autoConnect = autoConnect;
1384
    }
1385

    
1386
    public boolean isDevRemoteSource() {
1387
        return isDevRemoteSource;
1388
    }
1389

    
1390
    public void setDevRemoteSource(boolean isDevRemoteSource) {
1391
        this.isDevRemoteSource = isDevRemoteSource;
1392
    }
1393

    
1394
    public String getInstanceName() {
1395
        return instanceName;
1396
    }
1397

    
1398
    public void setInstanceName(String instanceName) {
1399
        this.instanceName = instanceName;
1400
    }
1401

    
1402
    @Override
1403
    public void handleError(Throwable t) {
1404
        Display.getDefault().syncExec(()-> {
1405
            serverJob.cancel();
1406

    
1407
            String title = Messages.RemotingLoginDialog_SERVER_LAUNCH_ERROR;
1408
            String  message = t.getMessage();
1409

    
1410
            MessagingUtils.errorDialog(title,
1411
                    this,
1412
                    message,
1413
                    TaxeditorStorePlugin.PLUGIN_ID,
1414
                    t,
1415
                    true);
1416
        });
1417

    
1418
    }
1419
}
(5-5/8)