Project

General

Profile

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

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

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

    
61
import eu.etaxonomy.cdm.api.application.CdmApplicationRemoteConfiguration;
62
import eu.etaxonomy.cdm.api.application.CdmApplicationState;
63
import eu.etaxonomy.cdm.api.service.IUserService;
64
import eu.etaxonomy.cdm.model.metadata.CdmMetaData;
65
import eu.etaxonomy.cdm.persistence.hibernate.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.server.CDMServerUtils;
72
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
73
import eu.etaxonomy.taxeditor.remoting.source.CdmServerInfo;
74
import eu.etaxonomy.taxeditor.remoting.source.CdmServerInfo.CdmInstanceInfo;
75
import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
76
import eu.etaxonomy.taxeditor.store.CdmStore;
77
import eu.etaxonomy.taxeditor.store.LoginManager;
78
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
79
import eu.etaxonomy.taxeditor.webapp.CDMEmbeddedServerException;
80
import eu.etaxonomy.taxeditor.webapp.CDMServer;
81
import eu.etaxonomy.taxeditor.webapp.ICDMServerError;
82

    
83

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

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

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

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

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

    
115
    private final static String MESG_COMPATIBLE_EDITOR_OLD = Messages.RemotingLoginDialog_UPDATE_EDITOR;
116
    private final static String MESG_COMPATIBLE_SERVER_OLD = Messages.RemotingLoginDialog_CHOOSE_COMPATIBLE_CDM_SERVER;
117

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

    
120
    private final static String LOGIN_NODE = "login"; //$NON-NLS-1$
121
    private final static String USERNAME_SUFFIX = "_username"; //$NON-NLS-1$
122
    private final static String PASSWORD_SUFFIX = "_password"; //$NON-NLS-1$
123

    
124
    private final static String LAST_SERVER_INSTANCE_NODE = "lastServerInstance"; //$NON-NLS-1$
125
    private final static String LAST_SERVER_KEY = "lastServerKey"; //$NON-NLS-1$
126
    private final static String LAST_INSTANCE_KEY = "lastInstanceKey"; //$NON-NLS-1$
127

    
128

    
129
    private Composite remotingComposite;
130
    private CdmServerInfo selectedCsii;
131
    private CdmInstanceInfo selectedCdmInstance;
132
    private Button btnCdmServerRefresh;
133
    private Button btnCdmInstanceRefresh;
134
    private Button btnStopServer;
135
    private Composite loginComposite;
136
    private Label lblLogin;
137
    private Text txtLogin;
138
    private Label lblPassword;
139
    private Text txtPassword;
140
    private Button btnRememberMe;
141
    private Composite compAdvanced;
142
    private Label lblPort;
143
    private Text txtPort;
144
    private Label lblServerVersion;
145
    private Text txtServerVersion;
146
    private ExpandableComposite xpndblcmpstAdvanced;
147
    private StyledText styledTxtMessage;
148

    
149

    
150
//    private final int MIN_WIDTH = 530;
151
//    private final int MIN_HEIGHT = 220;
152
//    private final int MIN_EXP_HEIGHT = 380;
153
    private final int MESSAGE_HEIGHT = 50;
154
    private Label lblEditorVersion;
155
    private Text txtEditorVersion;
156
    private Label lblServerCDMVersion;
157
    private Text txtServerCDMVersion;
158
    private Label lblEditorCDMVersion;
159
    private Text txtEditorCDMVersion;
160

    
161
    private String serverName, instanceName;
162
    private boolean autoConnect = false;
163
    private boolean loadLoginPrefs = true;
164
    private boolean isDevRemoteSource = false;
165
    private Job serverJob;
166
    /**
167
     * Create the dialog.
168
     * @param parent
169
     * @param style
170
     */
171
    public RemotingLoginDialog(Shell parent, int style) {
172
        super(parent, style);
173
        setText(Messages.RemotingLoginDialog_LABEL_LOGIN);
174
    }
175

    
176
    public Object open(CdmRemoteSource source, boolean loadLoginPrefs, boolean autoConnect) {
177
        this.loadLoginPrefs = loadLoginPrefs;
178
        this.serverName = source.getName();
179
        String contextPath = source.getContextPath();
180
        this.instanceName = contextPath.substring(contextPath.lastIndexOf("/") + 1); //$NON-NLS-1$
181
        return open(serverName, instanceName, loadLoginPrefs, autoConnect);
182
    }
183

    
184

    
185
    public Object open(String serverName, String instanceName, boolean loadLoginPrefs, boolean autoConnect) {
186
        this.serverName = serverName;
187
        this.instanceName = instanceName;
188
        this.loadLoginPrefs = loadLoginPrefs;
189
        this.autoConnect = autoConnect;
190
        return open();
191
    }
192

    
193
    /**
194
     * Open the dialog.
195
     * @return the result
196
     */
197
    public Object open() {
198

    
199
        createContents();
200
        if(serverName == null && instanceName == null) {
201
            readPrefLastServerInstance();
202
        }
203

    
204
        setEditorInfo();
205
        populateCdmServerCombo();
206
        shlConnect.open();
207
        shlConnect.layout();
208
        Point newSize = shlConnect.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
209
        shlConnect.setSize(newSize);
210

    
211
        xpndblcmpstAdvanced.setExpanded(false);
212

    
213
        Display display = getParent().getDisplay();
214

    
215
        while (!shlConnect.isDisposed()) {
216
            if (!display.isDisposed()){
217
                if (!display.readAndDispatch()) {
218
                    display.sleep();
219
                }
220
            }
221
        }
222

    
223
        return result;
224
    }
225

    
226
    /**
227
     * Create contents of the dialog.
228
     */
229
    private void createContents() {
230
        shlConnect = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE);
231
        //shlConnect.setMinimumSize(new Point(MIN_WIDTH, MIN_HEIGHT));
232
        // shlConnect.setSize(MIN_WIDTH, MIN_HEIGHT);
233
        shlConnect.setText(Messages.RemotingLoginDialog_LABEL_CONNECT);
234
        shlConnect.setLayout(new FillLayout(SWT.HORIZONTAL));
235

    
236
        remotingComposite = new Composite(shlConnect, SWT.NONE);
237
        remotingComposite.setLayout(new GridLayout(1, false));
238

    
239
        Composite cdmServerComposite = new Composite(remotingComposite, SWT.NONE);
240
        GridData gd_cdmServerComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
241
        // gd_cdmServerComposite.heightHint = 68;
242
        cdmServerComposite.setLayoutData(gd_cdmServerComposite);
243
        cdmServerComposite.setLayout(new GridLayout(4, false));
244

    
245
        Label lblCdmServer = new Label(cdmServerComposite, SWT.NONE);
246
        lblCdmServer.setText(Messages.RemotingLoginDialog_LABEL_CDM_SERVER);
247
        lblCdmServer.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
248
        lblCdmServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
249

    
250
        comboCdmServer = new Combo(cdmServerComposite, SWT.READ_ONLY);
251
        comboCdmServer.addSelectionListener(new SelectionAdapter() {
252
            @Override
253
            public void widgetSelected(SelectionEvent e) {
254
                refreshCdmServer();
255

    
256
            }
257
        });
258
        GridData gd_comboCdmServer = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
259
        //gd_comboCdmServer.widthHint = 150;
260
        comboCdmServer.setLayoutData(gd_comboCdmServer);
261
        comboCdmServer.select(0);
262

    
263
        txtCdmServerStatus = new Text(cdmServerComposite, SWT.BORDER);
264
        txtCdmServerStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
265
        txtCdmServerStatus.setEditable(false);
266
        GridData gd_txtCdmServerStatus = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
267
        //gd_txtCdmServerStatus.widthHint = 100;
268

    
269
        txtCdmServerStatus.setLayoutData(gd_txtCdmServerStatus);
270

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

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

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

    
300
        txtCdmInstanceStatus = new Text(cdmServerComposite, SWT.BORDER);
301
        txtCdmInstanceStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
302
        txtCdmInstanceStatus.setEditable(false);
303
        GridData gd_txtCdmInstanceStatus = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
304
        //gd_txtCdmInstanceStatus.widthHint = 100;
305
        txtCdmInstanceStatus.setLayoutData(gd_txtCdmInstanceStatus);
306

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

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

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

    
336
        txtLogin = new Text(loginComposite, SWT.BORDER);
337
        GridData gd_txtLogin = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
338
        gd_txtLogin.minimumWidth = 80;
339
//        gd_txtLogin.widthHint = 80;
340
//        gd_txtLogin.heightHint = 15;
341
        txtLogin.setLayoutData(gd_txtLogin);
342

    
343
        lblPassword = new Label(loginComposite, SWT.CENTER);
344
        lblPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
345
        lblPassword.setText(Messages.RemotingLoginDialog_LABEL_PASSWORD);
346
        lblPassword.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
347

    
348
        txtPassword = new Text(loginComposite, SWT.BORDER | SWT.PASSWORD);
349
        GridData gd_txtPassword = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
350
        gd_txtPassword.minimumWidth = 80;
351
//        gd_txtPassword.widthHint = 80;
352
//        gd_txtPassword.heightHint = 15;
353
        txtPassword.setLayoutData(gd_txtPassword);
354
        new Label(loginComposite, SWT.NONE);
355
        txtPassword.addKeyListener(new KeyAdapter() {
356
        	@Override
357
        	public void keyPressed(KeyEvent e) {
358
        		if(e.character==SWT.CR){
359
        			connectButtonPressed();
360
        		}
361
        	}
362
        });
363

    
364
        btnConnect = new Button(loginComposite, SWT.FLAT);
365
        btnConnect.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
366
        btnConnect.addSelectionListener(new SelectionAdapter() {
367
			@Override
368
			public void widgetSelected(SelectionEvent e) {
369
				connectButtonPressed();
370
			}
371
		});
372
        btnConnect.setText(Messages.RemotingLoginDialog_LABEL_CONNECT);
373

    
374
        btnRememberMe = new Button(loginComposite, SWT.CHECK);
375
        btnRememberMe.setSelection(true);
376
        GridData gd_btnRememberMe = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1);
377
        btnRememberMe.setLayoutData(gd_btnRememberMe);
378
        btnRememberMe.setText(Messages.RemotingLoginDialog_LABEL_REMEMBER_ME);
379

    
380
        Label lblDefaultLogin = new Label(loginComposite, SWT.NONE);
381
        GridDataFactory.fillDefaults().span(4, 1).align(SWT.TRAIL, SWT.CENTER).applyTo(lblDefaultLogin);
382
        lblDefaultLogin.setText(String.format(Messages.RemotingLoginDialog_DEFAULT_LOGIN, DEFAULT_USER, DEFAULT_PASS));
383

    
384
        styledTxtMessage = new StyledText(remotingComposite, SWT.NONE);
385
        styledTxtMessage.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
386
        styledTxtMessage.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
387
        styledTxtMessage.setFont(SWTResourceManager.getFont(UBUNTU, 12, SWT.BOLD));
388
        styledTxtMessage.setSelectionBackground(SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION_TEXT));
389
        styledTxtMessage.setSelectionForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_RED));
390
        styledTxtMessage.setDoubleClickEnabled(false);
391
        styledTxtMessage.setEditable(false);
392
        styledTxtMessage.setWordWrap(true);
393

    
394
        GridData gd_styledTxtMessage = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
395
        gd_styledTxtMessage.exclude = true;
396
        gd_styledTxtMessage.minimumHeight = MESSAGE_HEIGHT;
397
        // gd_styledTxtMessage.heightHint = MESSAGE_HEIGHT;
398
        //gd_styledTxtMessage.widthHint = MIN_WIDTH - 5;
399

    
400
        styledTxtMessage.setLayoutData(gd_styledTxtMessage);
401

    
402
        xpndblcmpstAdvanced = new ExpandableComposite(remotingComposite, SWT.NONE, ExpandableComposite.TWISTIE);
403
        GridData gd_xpndblcmpstAdvanced = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1);
404
        // gd_xpndblcmpstAdvanced.heightHint = 19;
405
        // gd_xpndblcmpstAdvanced.widthHint = MIN_WIDTH - 10;
406
        xpndblcmpstAdvanced.setLayoutData(gd_xpndblcmpstAdvanced);
407
        xpndblcmpstAdvanced.addExpansionListener(new IExpansionListener() {
408
            @Override
409
            public void expansionStateChanged(ExpansionEvent e) {
410
                if(e.getState()) {
411
                    Point newSize = shlConnect.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
412
                    shlConnect.setSize(newSize);
413
                } else {
414
                    Point newSize = shlConnect.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
415
                    shlConnect.setSize(newSize);
416
                }
417

    
418
            }
419
            @Override
420
            public void expansionStateChanging(ExpansionEvent e) {
421
            }
422
        });
423
        xpndblcmpstAdvanced.setText(Messages.RemotingLoginDialog_LABEL_ADVANCED);
424
        xpndblcmpstAdvanced.setExpanded(true);
425

    
426
        compAdvanced = new Composite(xpndblcmpstAdvanced, SWT.NONE);
427
        xpndblcmpstAdvanced.setClient(compAdvanced);
428
        compAdvanced.setLayout(new GridLayout(4, false));
429

    
430
        lblPort = new Label(compAdvanced, SWT.CENTER);
431
        lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
432
        //lblPort.setSize(0, 0);
433
        lblPort.setText(Messages.RemotingLoginDialog_LABEL_PORT);
434
        lblPort.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
435

    
436
        txtPort = new Text(compAdvanced, SWT.BORDER);
437
        GridData gd_txtPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
438
        gd_txtPort.minimumWidth = 50;
439
        // gd_txtPort.widthHint = 50;
440
        txtPort.setLayoutData(gd_txtPort);
441

    
442
        lblServerVersion = new Label(compAdvanced, SWT.CENTER);
443
        lblServerVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
444
        lblServerVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDMLIB_VERSION);
445
        lblServerVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
446

    
447
        txtServerVersion = new Text(compAdvanced, SWT.BORDER);
448
        txtServerVersion.setEditable(false);
449
        txtServerVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
450
        btnStopServer = new Button(compAdvanced, SWT.FLAT);
451
        btnStopServer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
452
        btnStopServer.addMouseListener(new MouseAdapter() {
453
            @Override
454
            public void mouseUp(MouseEvent e) {
455
                stopManagedServer();
456
            }
457
        });
458
        btnStopServer.setText(Messages.RemotingLoginDialog_LABEL_STOP_MANAGED_SERVER);
459

    
460
        lblEditorVersion = new Label(compAdvanced, SWT.CENTER);
461
        lblEditorVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
462
        lblEditorVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDMLIB_VERSION);
463
        lblEditorVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
464

    
465
        txtEditorVersion = new Text(compAdvanced, SWT.BORDER);
466
        txtEditorVersion.setEditable(false);
467
        txtEditorVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
468
        new Label(compAdvanced, SWT.NONE);
469
        new Label(compAdvanced, SWT.NONE);
470

    
471
        lblServerCDMVersion = new Label(compAdvanced, SWT.CENTER);
472
        lblServerCDMVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
473
        lblServerCDMVersion.setText(Messages.RemotingLoginDialog_LABEL_SERVER_CDM_VERSION);
474
        lblServerCDMVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
475

    
476
        txtServerCDMVersion = new Text(compAdvanced, SWT.BORDER);
477
        txtServerCDMVersion.setEditable(false);
478
        txtServerCDMVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
479
        new Label(compAdvanced, SWT.NONE);
480
        new Label(compAdvanced, SWT.NONE);
481

    
482
        lblEditorCDMVersion = new Label(compAdvanced, SWT.CENTER);
483
        lblEditorCDMVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
484
        lblEditorCDMVersion.setText(Messages.RemotingLoginDialog_LABEL_EDITOR_CDM_VERSION);
485
        lblEditorCDMVersion.setFont(SWTResourceManager.getFont(UBUNTU, 9, SWT.NORMAL));
486

    
487
        txtEditorCDMVersion = new Text(compAdvanced, SWT.BORDER);
488
        txtEditorCDMVersion.setEditable(false);
489
        txtEditorCDMVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
490

    
491

    
492
    }
493

    
494
	private void connectButtonPressed() {
495
		if(selectedCsii.isLocalhostMgd() && !isSelectedCdmInstanceRunningInManagedServer()) {
496
			startManagedServer();
497
		} else {
498
			connect();
499
			if (CdmStore.isActive() && CdmStore.currentAuthentiationHasOneOfRoles(Role.ROLE_REMOTING)){
500
			    PreferencesUtil.setNomenclaturalCodePreferences();
501
			}
502

    
503
		}
504
	}
505

    
506
    private void populateCdmServerCombo() {
507
        Job job = new Job(Messages.RemotingLoginDialog_RETRIEVE_SERVER_INSTANCES) {
508
            @Override
509
            protected IStatus run(IProgressMonitor monitor) {
510
                Display.getDefault().syncExec(new Runnable() {
511
                    @Override
512
                    public void run() {
513
                        for(CdmServerInfo csii : CdmServerInfo.getCdmServers()) {
514
                            csiiMap.put(csii.getName(), csii);
515
                            comboCdmServer.add(csii.getName());
516
                        }
517
                        int serverIndex = -1;
518
                        if(serverName != null) {
519
                            serverIndex = comboCdmServer.indexOf(serverName);
520
                        }
521
                        if(serverIndex == -1) {
522
                            comboCdmServer.select(0);
523
                            autoConnect = false;
524
                        } else {
525
                            comboCdmServer.select(serverIndex);
526
                        }
527
                        CdmRemoteSource devRemoteSource = CdmServerInfo.getDevServerRemoteSource();
528
                        if(devRemoteSource != null) {
529
                            isDevRemoteSource = true;
530
                            String username = System.getProperty("cdm.server.dev.username"); //$NON-NLS-1$
531
                            String password = System.getProperty("cdm.server.dev.password"); //$NON-NLS-1$
532
                            if(username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
533
                                txtLogin.setText(username);
534
                                txtPassword.setText(password);
535
                                CdmStore.connect(devRemoteSource, RemotingLoginDialog.this);
536
                            }
537
                        } else {
538
                            refreshCdmServer();
539
                        }
540
                    }
541
                });
542
                return Status.OK_STATUS;
543
            }
544
        };
545
        job.schedule();
546
    }
547

    
548

    
549
    private void refreshCdmServer() {
550
        try{
551
            txtCdmServerStatus.setText(STATUS_CHECKING_AVAILABILITY);
552
            clearOnServerChange();
553
            emptyCredentials();
554
            updateSelectedCdmServer();
555
            Display.getDefault().asyncExec(new Runnable() {
556
                @Override
557
                public void run() {
558
                    checkSelectedCdmServer();
559
                }
560
            });
561
        }
562
        catch(SWTException e){
563
            //catch widget is disposed exception which may occurr if
564
            //dialog is closed but the runnable tries to update
565
        }
566
    }
567

    
568
    private void updateSelectedCdmServer() {
569
        int selIndex = comboCdmServer.getSelectionIndex();
570
        if(selIndex != -1) {
571
            selectedCsii = csiiMap.get(comboCdmServer.getItem(selIndex));
572
        }
573
    }
574

    
575
    private void updatePort() {
576
        txtPort.setText(""); //$NON-NLS-1$
577
        if(selectedCsii != null) {
578
            int port = selectedCsii.getPort();
579
            if(port == CdmServerInfo.NULL_PORT) {
580
                txtPort.setText(CdmServerInfo.NULL_PORT_STRING);
581
            } else {
582
                txtPort.setText(String.valueOf(port));
583
            }
584
        }
585
    }
586

    
587
    private int getPort() {
588
        int port = CdmServerInfo.NULL_PORT;
589
        try {
590
            port = Integer.valueOf(txtPort.getText());
591
        } catch (NumberFormatException nfe) {
592
            if(!CdmServerInfo.NULL_PORT_STRING.equals(txtPort.getText())) {
593
                setMessage(Messages.RemotingLoginDialog_MESSAGE_PORT_SHOULD_BE_INTEGER);
594
            }
595
        }
596
        return port;
597
    }
598

    
599
    private void checkSelectedCdmServer() {
600
        try{
601
            if(selectedCsii != null) {
602
                if(selectedCsii.isLocalhost()) {
603
                    txtPort.setEditable(true);
604
                    txtPort.setEnabled(true);
605
                }
606
                try {
607
                    if(selectedCsii.pingServer()) {
608
                        txtCdmServerStatus.setText(STATUS_AVAILABLE);
609
                        populateCdmInstanceCombo(true);
610
                        String serverVersionTimestamp = generateLastModifiedTooltip(selectedCsii.getCdmlibLastModified());
611
                        txtServerVersion.setText(selectedCsii.getCdmlibServicesVersion() + ":" + serverVersionTimestamp); //$NON-NLS-1$
612
                    } else {
613
                        txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
614
                        comboCdmInstance.removeAll();
615
                        disableCdmInstanceControls("", ""); //$NON-NLS-1$ //$NON-NLS-2$
616
                    }
617
                } catch (CDMServerException | IOException e) {
618
                    txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
619
                    // TODO distinguish java.net.ConnectException: Connection refused, java.net.SocketTimeoutException: Read timed out
620
                    Throwable cause = e;
621
                    if(e instanceof CDMServerException && e.getCause() != null){
622
                        cause = e.getCause();
623
                    }
624
                    String message = Messages.RemotingLoginDialog_CONNECTION_FAILED_MESSAGE;
625
                    if(cause instanceof SocketTimeoutException){
626
                        message = Messages.RemotingLoginDialog_CONNECTION_TIMEOUT_MESSAGE;
627
                    }
628
                    MessagingUtils.warningDialog(Messages.RemotingLoginDialog_CONNECTION_FAILED_TITLE, this,
629
                            message);
630
                    logger.warn(Messages.RemotingLoginDialog_CONNECTION_FAILED_TITLE, e);
631
                }
632
            }
633
            updatePort();
634
        }
635
        catch(SWTException e){
636
            //catch widget is disposed exception which may occurr if
637
            //dialog is closed but the runnable tries to update
638
        }
639
    }
640

    
641

    
642
    private void populateCdmInstanceCombo(final boolean forceRefresh) {
643
        comboCdmInstance.removeAll();
644
        comboCdmInstance.setEnabled(false);
645
        btnConnect.setEnabled(false);
646
        txtCdmInstanceStatus.setText(STATUS_RETRIEVING);
647
        txtCdmInstanceStatus.setToolTipText(""); //$NON-NLS-1$
648

    
649
        serverJob = new Job(Messages.RemotingLoginDialog_RETRIEVE_SERVER_INSTANCES) {
650
            @Override
651
            protected IStatus run(IProgressMonitor monitor) {
652
                try {
653
                    if(selectedCsii != null) {
654
                        if(forceRefresh) {
655
                            selectedCsii.refreshInstances();
656
                        }
657
                        final List<CdmInstanceInfo> instances = selectedCsii.getInstances();
658
                        Display.getDefault().asyncExec(new Runnable() {
659
                            @Override
660
                            public void run() {
661
                                if(!instances.isEmpty()) {
662
                                    for(CdmInstanceInfo cdmInstance : instances) {
663
                                        comboCdmInstance.add(cdmInstance.getName());
664
                                    }
665
                                    int instanceIndex = -1;
666
                                    if(instanceName != null) {
667
                                        instanceIndex = comboCdmInstance.indexOf(instanceName);
668
                                    }
669
                                    if(instanceIndex == -1) {
670
                                        comboCdmInstance.select(0);
671
                                        autoConnect = false;
672
                                    } else {
673
                                        comboCdmInstance.select(instanceIndex);
674
                                    }
675
                                    refreshCdmInstance();
676
                                    comboCdmInstance.setEnabled(true);
677
                                    if(autoConnect) {
678
                                        connect();
679
                                    }
680

    
681
                                } else {
682
                                    txtCdmInstanceStatus.setText(STATUS_NO_INSTANCES);
683
                                    btnConnect.setEnabled(false);
684
                                }
685
                            }
686
                        });
687
                    }
688
                } catch (final CDMServerException e) {
689
                    MessagingUtils.warn(getClass(), e);
690
                    Display.getDefault().asyncExec(new Runnable() {
691
                        @Override
692
                        public void run() {
693
                            disableCdmInstanceControls(STATUS_NOT_AVAILABLE, e.getMessage());
694
                        }
695
                    });
696
                }
697
                return Status.OK_STATUS;
698
            }
699
        };
700

    
701
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE) && !isDevRemoteSource) {
702
            // Start the Job
703
            serverJob.schedule();
704
        }
705
    }
706

    
707
    private void disableCdmInstanceControls(String cdmInstanceStatus, String tooltip) {
708
        txtCdmInstanceStatus.setText(cdmInstanceStatus);
709
        txtCdmInstanceStatus.setToolTipText(tooltip);
710
        comboCdmInstance.setEnabled(false);
711
        btnConnect.setEnabled(false);
712

    
713
    }
714
    private void refreshCdmInstance() {
715
        txtCdmInstanceStatus.setText(STATUS_CHECKING_AVAILABILITY);
716
        clearOnInstanceChange();
717
        updateSelectedCdmInstance();
718
        checkSelectedCdmInstance();
719
        updateManagedServerControls();
720
    }
721

    
722
    private void updateSelectedCdmInstance() {
723
        int selIndex = comboCdmInstance.getSelectionIndex();
724
        if(selIndex != -1) {
725
            selectedCdmInstance = selectedCsii.getInstanceFromName(comboCdmInstance.getItem(selIndex));
726

    
727
            if(loadLoginPrefs) {
728
                readPrefCredentials();
729
            }
730
        }
731
    }
732

    
733
    private void updateManagedServerControls() {
734
        if(selectedCsii.isLocalhostMgd()) {
735
            if(isSelectedCdmInstanceRunningInManagedServer()) {
736
                txtCdmInstanceStatus.setText(STATUS_STARTED);
737
            } else {
738
                txtCdmInstanceStatus.setText(STATUS_NOT_STARTED);
739
            }
740
            btnConnect.setEnabled(true);
741
            selectedCsii.setPort(getManagedServerPort());
742
            updatePort();
743
        }
744

    
745

    
746
        if(isManagedServerRunning()) {
747
            btnStopServer.setEnabled(true);
748
        } else {
749
            btnStopServer.setEnabled(false);
750
        }
751
    }
752

    
753
    private boolean isManagedServerRunning() {
754
        return CdmStore.getManagedServer() != null && CdmStore.getManagedServer().isAlive();
755
    }
756

    
757
    private boolean isSelectedCdmInstanceRunningInManagedServer() {
758
        return CdmStore.getManagedServer() != null &&
759
                CdmStore.getManagedServer().isAlive() &&
760
                selectedCsii.isLocalhostMgd() &&
761
                CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName());
762
    }
763

    
764
    private void startManagedServer() {
765
        if(isManagedServerRunning()) {
766
            if(CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())) {
767
                return;
768
            } else {
769
                Display.getDefault().syncExec(new Runnable() {
770
                    @Override
771
                    public void run() {
772
                        stopManagedServer();
773
                    }
774
                });
775
            }
776
        }
777

    
778

    
779
        Job job = new Job(Messages.RemotingLoginDialog_JOB_SERVER_LAUNCH) {
780

    
781
            @Override
782
            public IStatus run(IProgressMonitor monitor) {
783
                String mgdServerConfigFileName = "mgd.datasources.xml"; //$NON-NLS-1$
784
                String config = CDMServerUtils.convertEditorToServerConfig();
785
                File managedServerConfigFile;
786
                int maxUnits = 50;
787
                monitor.beginTask(Messages.RemotingLoginDialog_TASK_LAUNCHING_SERVER, maxUnits);
788
                try {
789
                    monitor.subTask(String.format(Messages.RemotingLoginDialog_GENERATING_CONFIG_FILE, selectedCdmInstance.getName()));
790
                    managedServerConfigFile = CDMServerUtils.writeManagedServerConfig(config, mgdServerConfigFileName);
791
                    monitor.worked(1);
792
                    boolean forceSchemaCreate = CdmStore.getManagedServer() != null
793
                            && CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())
794
                            && CdmStore.getManagedServer().isForceSchemaCreate();
795
                    CdmStore.setManagedServer(new CDMServer(selectedCdmInstance.getName(), managedServerConfigFile));
796
                    CdmStore.getManagedServer().setForceSchemaCreate(forceSchemaCreate);
797
                    monitor.subTask(Messages.RemotingLoginDialog_STARTING_MGD_SERVER);
798
                    CdmStore.getManagedServer().start(false, RemotingLoginDialog.this);
799
                    int serverUnits = 0;
800

    
801
                    // the following loop is a 'fake' progress monitoring where the progress
802
                    // bar is advanced by one unit every second until maxUnits -2
803
                    while(!CdmStore.getManagedServer().isStarted() && !CdmStore.getManagedServer().isFailed()) {
804
                        if(serverUnits < maxUnits - 2) {
805
                            try {
806
                                Thread.sleep(1000);
807
                            } catch (InterruptedException e) {
808
                            }
809
                            monitor.worked(1);
810
                            serverUnits++;
811
                        }
812
                    }
813
                    Display.getDefault().asyncExec(new Runnable() {
814
                        @Override
815
                        public void run() {
816
                                hide(false);
817
                                updateManagedServerControls();
818
                                connect();
819
                            }
820
                    });
821
                } catch (IOException ioe) {
822
                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_GENERATING_CONFIG_FILE,
823
                            this,
824
                            ioe.getMessage(),
825
                            TaxeditorStorePlugin.PLUGIN_ID,
826
                            ioe,
827
                            true);
828
                } catch (CDMEmbeddedServerException cse) {
829
                    MessagingUtils.errorDialog(Messages.RemotingLoginDialog_ERROR_STARTING_SERVER,
830
                                this,
831
                                cse.getMessage(),
832
                                TaxeditorStorePlugin.PLUGIN_ID,
833
                                cse,
834
                                true);
835
                } finally {
836
                    monitor.done();
837
                }
838
                // NOTE: Errors thrown during server startup are passed to the handleError() implementation
839
                // TODO: is the above catch clause for CDMEmbeddedServerException still valuable?
840

    
841
                return Status.OK_STATUS;
842
            }
843
        };
844

    
845
        // configure the job
846
        job.setProperty(IProgressConstants.KEEP_PROPERTY, true);
847
        job.setUser(true);
848
        // schedule job
849
        hide(true);
850
        job.schedule();
851
    }
852

    
853

    
854
    @Override
855
    public void handleError(final Throwable t) {
856

    
857
        if(CdmStore.getManagedServer().isFailed() && CdmStore.getManagedServer().isPotentiallyMissingSchema()) {
858
            CdmStore.getManagedServer().setForceSchemaCreate(true);
859
            // we are in a separate thread here, thus update the screen via
860
            Display.getDefault().asyncExec(new Runnable() {
861
                @Override
862
                public void run() {
863
                    btnConnect.setEnabled(true);
864
                    btnConnect.setText("Create Schema");
865
                    btnConnect.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_RED));
866
                }
867
             });
868
        } else {
869
            Display.getDefault().syncExec(new Runnable() {
870
                @Override
871
                public void run() {
872
                    serverJob.cancel();
873

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

    
877

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

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

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

    
908
    private void checkSelectedCdmInstance() {
909
        boolean available = false;
910
        String status = STATUS_NOT_AVAILABLE;
911
        String message = null;
912

    
913
        if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE)) {
914
            try {
915
                if(selectedCsii.pingInstance(selectedCdmInstance, getPort())) {
916
                    status = STATUS_AVAILABLE;
917
                    available = true;
918
                } else {
919
                    status = STATUS_NOT_AVAILABLE;
920
                    available = false;
921
                }
922

    
923
                if(available) {
924
                    txtServerCDMVersion.setText(selectedCsii.getCdmRemoteSource(selectedCdmInstance, getPort()).getDbSchemaVersion());
925
                    int compareDbSchemaVersion = selectedCsii.compareDbSchemaVersion(selectedCdmInstance, getPort());
926
                    int compareCdmlibServicesVersion = 0;
927
                    boolean disableServicesApiTimestampCheck =
928
                            PreferencesUtil.getBooleanValue((IPreferenceKeys.DISABLE_SERVICES_API_TIMESTAMP_CHECK));
929
                    if(!disableServicesApiTimestampCheck) {
930
                        compareCdmlibServicesVersion = selectedCsii.compareCdmlibServicesVersion();
931
                    }
932
                    if(compareDbSchemaVersion > 0 || compareCdmlibServicesVersion > 0) {
933
                        status =  STATUS_NOT_COMPATIBLE;
934
                        available = false;
935
                        message = MESG_COMPATIBLE_EDITOR_OLD;
936
                    } else if(compareDbSchemaVersion < 0 || compareCdmlibServicesVersion < 0) {
937
                        status = STATUS_NOT_COMPATIBLE;
938
                        available = false;
939
                        message = MESG_COMPATIBLE_SERVER_OLD;
940
                    } else {
941
                        status =  STATUS_AVAILABLE;
942
                        available = true;
943
                        message = ""; //$NON-NLS-1$
944
                    }
945
                }
946
            } catch (Exception e) {
947
                txtCdmInstanceStatus.setToolTipText(e.getMessage());
948
            } finally {
949
                btnConnect.setEnabled(available);
950
                txtCdmInstanceStatus.setText(status);
951
                if(!StringUtils.isBlank(message)) {
952
                    setMessage(message);
953
                }
954
            }
955
        }
956
    }
957

    
958
    private void connect() {
959
        checkSelectedCdmInstance();
960

    
961
        if(!txtCdmInstanceStatus.getText().equals(STATUS_AVAILABLE)) {
962
            return;
963
        }
964

    
965
        ICdmRemoteSource source = selectedCsii.getCdmRemoteSource(selectedCdmInstance, getPort());
966

    
967
        if(!validateLogin(source)) {
968
            return;
969
        }
970

    
971
        try {
972
            CdmStore.connect(source, this);
973
        } catch (Exception e) {
974
            // Do not expect anything to go wrong at this point, so we throw a runtime exception
975
            // if any problems
976
            throw new RuntimeException(e);
977
        }
978

    
979
    }
980

    
981
    public boolean isRememberMe() {
982
        return btnRememberMe.getSelection();
983
    }
984

    
985
    private void persistPrefLastServerInstance() {
986
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
987
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
988

    
989
        lastServerInstancePrefs.put(LAST_SERVER_KEY, selectedCsii.getName());
990
        lastServerInstancePrefs.put(LAST_INSTANCE_KEY, selectedCdmInstance.getName());
991

    
992
        flushPreferences(lastServerInstancePrefs);
993
    }
994

    
995
    private void persistPrefCredentials() {
996
         IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
997
         Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
998
         credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
999
         credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
1000
         flushPreferences(credentialsPrefs);
1001
    }
1002

    
1003
    private void removePrefCredentials() {
1004
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1005
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1006
        credentialsPrefs.put(getUsernamePrefKey(), txtLogin.getText());
1007
        credentialsPrefs.put(getPasswordPrefKey(), txtPassword.getText());
1008
        removePreferences(credentialsPrefs);
1009
   }
1010
    private void removePreferences(Preferences prefs) {
1011
        try {
1012
            prefs.removeNode();
1013
        } catch (BackingStoreException bse) {
1014
            setMessage(bse.getMessage());
1015
        }
1016
    }
1017
    private void flushPreferences(Preferences prefs) {
1018
        try {
1019
            prefs.flush();
1020
        } catch (BackingStoreException bse) {
1021
            setMessage(bse.getMessage());
1022
        }
1023
    }
1024

    
1025

    
1026

    
1027
    private void readPrefCredentials() {
1028
        String username, password;
1029
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1030
        Preferences credentialsPrefs = preferences.node(LOGIN_NODE);
1031
        username = credentialsPrefs.get(getUsernamePrefKey(), ""); //$NON-NLS-1$
1032
        txtLogin.setText(username);
1033
        password = credentialsPrefs.get(getPasswordPrefKey(),""); //$NON-NLS-1$
1034
        txtPassword.setText(password);
1035
        if(username.isEmpty() || password.isEmpty()) {
1036
            autoConnect = false;
1037
        }
1038
    }
1039

    
1040
    private void readPrefLastServerInstance() {
1041
        IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode(STORE_PREFERENCES_NODE);
1042
        Preferences lastServerInstancePrefs = preferences.node(LAST_SERVER_INSTANCE_NODE);
1043

    
1044
        serverName = lastServerInstancePrefs.get(LAST_SERVER_KEY, null);
1045
        instanceName = lastServerInstancePrefs.get(LAST_INSTANCE_KEY, null);
1046
    }
1047

    
1048
    private void emptyCredentials() {
1049
        txtLogin.setText(""); //$NON-NLS-1$
1050
        txtPassword.setText(""); //$NON-NLS-1$
1051
    }
1052

    
1053
    private String getUsernamePrefKey() {
1054
        return selectedCsii.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + USERNAME_SUFFIX;
1055
    }
1056

    
1057
    private String getPasswordPrefKey() {
1058
        return selectedCsii.toString(selectedCdmInstance.getName(), isDevRemoteSource?getPort():-1) + PASSWORD_SUFFIX;
1059
    }
1060

    
1061
    private boolean validateLogin(ICdmRemoteSource remoteSource) {
1062
        if(getUsername() == null || getUsername().isEmpty()) {
1063
            setMessage(Messages.RemotingLoginDialog_LOGIN_CANNOT_BE_EMPTY);
1064
            return false;
1065
        }
1066
        if(getPassword() == null || getPassword().isEmpty()) {
1067
            setMessage(Messages.RemotingLoginDialog_PASSWORD_CANNOT_BE_EMPTY);
1068
            return false;
1069
        }
1070

    
1071

    
1072
        try {
1073
            IUserService userService = CdmApplicationRemoteConfiguration.getUserService(remoteSource);
1074
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(getUsername(), getPassword());
1075
            CdmApplicationRemoteConfiguration.getAuthenticationManager(userService).authenticate(token);
1076
        } catch(BadCredentialsException e){
1077
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1078
            return false;
1079
        } catch(LockedException e){
1080
            setMessage(LoginManager.ACCOUNT_LOCKED_MESSAGE);
1081
            return false;
1082
        } catch(IllegalArgumentException e){
1083
            setMessage(LoginManager.INCORRECT_CREDENTIALS_MESSAGE);
1084
            return false;
1085
        }
1086
        return true;
1087
    }
1088

    
1089
    public String getUsername() {
1090
        return txtLogin.getText();
1091
    }
1092

    
1093
    public String getPassword() {
1094
        return txtPassword.getText();
1095
    }
1096

    
1097
    public void setMessage(String message) {
1098
        if(message != null && !message.isEmpty()) {
1099
//            if(message.length() > 50) {
1100
//                styledTxtMessage.setToolTipText(message);
1101
//                message = message.substring(0,50) + "..."; //$NON-NLS-1$
1102
//            }
1103
            styledTxtMessage.setText(message);
1104
            styledTxtMessage.setVisible(true);
1105
            ((GridData)styledTxtMessage.getLayoutData()).exclude = false;
1106
//            shlConnect.setMinimumSize(MIN_WIDTH, getHeightWithoutMessage() + MESSAGE_HEIGHT);
1107
            Point newSize = shlConnect.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
1108
            shlConnect.setSize(newSize);
1109
        } else {
1110
            if (!styledTxtMessage.isDisposed()){
1111
                styledTxtMessage.setText(""); //$NON-NLS-1$
1112
                styledTxtMessage.setVisible(false);
1113
                ((GridData)styledTxtMessage.getLayoutData()).exclude = true;
1114
            }
1115
            if(!shlConnect.isDisposed()){
1116
//                shlConnect.setMinimumSize(MIN_WIDTH, getHeightWithoutMessage());
1117
                Point newSize = shlConnect.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
1118
                shlConnect.setSize(newSize);
1119
            }
1120
        }
1121
        if (!remotingComposite.isDisposed()){
1122
            remotingComposite.layout();
1123
        }
1124
    }
1125

    
1126
//    private int getHeightWithoutMessage() {
1127
//        if(xpndblcmpstAdvanced.isExpanded()) {
1128
//            return MIN_EXP_HEIGHT;
1129
//        } else {
1130
//            return MIN_HEIGHT;
1131
//        }
1132
//    }
1133

    
1134

    
1135
    public void hide(boolean isHidden) {
1136
        if (!shlConnect.isDisposed()){
1137
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1138
                shlConnect.setVisible(!isHidden);
1139
            }
1140
        }
1141
    }
1142
    public void dispose() {
1143
        if (!shlConnect.isDisposed()){
1144
            if(shlConnect != null && shlConnect.getDisplay() != null) {
1145
                shlConnect.dispose();
1146
            }
1147
        }
1148
    }
1149

    
1150
    public void onComplete() {
1151
        Display.getDefault().asyncExec(new Runnable() {
1152
            @Override
1153
            public void run() {
1154
                if(selectedCdmInstance!=null){
1155
                    if(isRememberMe()) {
1156
                        persistPrefCredentials();
1157
                    }else{
1158
                        removePrefCredentials();
1159
                    }
1160
                    persistPrefLastServerInstance();
1161
                }
1162
                dispose();
1163
            }
1164
        });
1165
    }
1166

    
1167
    private String generateLastModifiedTooltip(String cdmlibLastModified) {
1168
        if(StringUtils.isBlank(cdmlibLastModified)) {
1169
            return ""; //$NON-NLS-1$
1170
        }
1171
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.z"); //$NON-NLS-1$
1172
        Date cdmlibLastModifiedDate;
1173
        String cdmlibLastModifiedTimestamp = ""; //$NON-NLS-1$
1174

    
1175
        cdmlibLastModifiedDate = new Date(Long.valueOf(cdmlibLastModified));
1176
        cdmlibLastModifiedTimestamp = sdf.format(cdmlibLastModifiedDate);
1177

    
1178
        return cdmlibLastModifiedTimestamp;
1179
    }
1180

    
1181
    private void setEditorInfo() {
1182
        txtEditorCDMVersion.setText(CdmMetaData.getDbSchemaVersion());
1183
        String editorVersionTimestamp = generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified());
1184
        txtEditorVersion.setText(CdmApplicationState.getCdmlibVersion() + ":" + editorVersionTimestamp); //$NON-NLS-1$
1185
    }
1186

    
1187
    private void clearOnServerChange() {
1188
        setMessage(""); //$NON-NLS-1$
1189
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1190
        txtServerVersion.setText(""); //$NON-NLS-1$
1191
        txtServerVersion.setToolTipText(""); //$NON-NLS-1$
1192
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1193
        comboCdmInstance.removeAll();
1194
        txtCdmInstanceStatus.setText(""); //$NON-NLS-1$
1195
        txtPort.setEditable(false);
1196
        txtPort.setEnabled(false);
1197
    }
1198

    
1199
    private void clearOnInstanceChange() {
1200
        setMessage(""); //$NON-NLS-1$
1201
        txtServerCDMVersion.setText(""); //$NON-NLS-1$
1202
    }
1203

    
1204

    
1205
}
(5-5/8)