Project

General

Profile

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

    
88
    private Logger logger = Logger.getLogger(getClass());
89

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

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

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

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

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

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

    
139
    public static final int BTN_COLOR_ATTENTION = SWT.COLOR_RED;
140

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

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

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

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

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

    
177
    protected Label lblEditorCdmlibVersion;
178
    protected Text txtEditorCdmlibVersion;
179
    protected Label lblServerSchemaVersion;
180
    protected Text txtServerSchemaVersion;
181
    protected Label lblEditorCdmVersion;
182
    protected Text txtEditorCdmVersion;
183

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

    
189
    private boolean autoConnect = false;
190
    protected boolean loadLoginPrefs = true;
191
    private boolean isDevRemoteSource = false;
192

    
193
    protected Job serverJob;
194
    protected Object result;
195

    
196
    private final Map<String, CdmServerInfo> serverInfoMap = new HashMap<>();
197

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
432
        styledTxtMessage.setLayoutData(gd_styledTxtMessage);
433

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

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

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

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

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

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

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

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

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

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

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

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

    
515
    }
516

    
517

    
518

    
519

    
520

    
521

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

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

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

    
574

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1106
        flushPreferences(lastServerInstancePrefs);
1107
    }
1108

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1288
        return cdmlibLastModifiedTimestamp;
1289
    }
1290

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

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

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

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

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

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

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

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

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

    
1346
        //message
1347
//        styledTxtMessage;
1348

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

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

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

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

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

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

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

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

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

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

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

    
1395
    public void setInstanceName(String instanceName) {
1396
        this.instanceName = instanceName;
1397
    }
1398
}
(5-5/8)