Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 400d1d3bb814ffa9daa2ea8bfb3c03402a7b8d36 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
/*
 * Copyright (c) 2004-2014 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.emf.cdo.explorer.ui.repositories.wizards;

import org.eclipse.emf.cdo.admin.CDOAdminClient;
import org.eclipse.emf.cdo.admin.CDOAdminClientManager;
import org.eclipse.emf.cdo.admin.CDOAdminClientRepository;
import org.eclipse.emf.cdo.admin.CDOAdminClientUtil;
import org.eclipse.emf.cdo.explorer.repositories.CDORepository.IDGeneration;
import org.eclipse.emf.cdo.explorer.repositories.CDORepository.VersioningMode;
import org.eclipse.emf.cdo.explorer.ui.ViewerUtil;
import org.eclipse.emf.cdo.explorer.ui.bundle.OM;
import org.eclipse.emf.cdo.net4j.CDONet4jSession;
import org.eclipse.emf.cdo.net4j.CDONet4jSessionConfiguration;
import org.eclipse.emf.cdo.net4j.CDONet4jUtil;
import org.eclipse.emf.cdo.session.CDORepositoryInfo;

import org.eclipse.net4j.Net4jUtil;
import org.eclipse.net4j.connector.IConnector;
import org.eclipse.net4j.util.container.ContainerEventAdapter;
import org.eclipse.net4j.util.container.ContainerUtil;
import org.eclipse.net4j.util.container.IContainer;
import org.eclipse.net4j.util.container.IManagedContainer;
import org.eclipse.net4j.util.event.IEvent;
import org.eclipse.net4j.util.event.IListener;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.eclipse.net4j.util.security.IPasswordCredentials;
import org.eclipse.net4j.util.security.IPasswordCredentialsProvider;
import org.eclipse.net4j.util.security.NotAuthenticatedException;
import org.eclipse.net4j.util.security.PasswordCredentialsProvider;
import org.eclipse.net4j.util.ui.views.ContainerItemProvider;

import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;

import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * @author Eike Stepper
 */
public class MasterRepositoryController
{
  private static final Image REPOSITORY_IMAGE = OM.getImage("icons/repository.gif");

  private static final Image EMPTY_IMAGE = OM.getImage("icons/empty.gif");

  private static final Image OK_IMAGE = OM.getImage("icons/ok.gif");

  private static final Image ERROR_IMAGE = PlatformUI.getWorkbench().getSharedImages()
      .getImage(ISharedImages.IMG_OBJS_ERROR_TSK);

  private static final int VALIDATING_WIDTH = 120;

  private final DisposeListener disposeListener = new DisposeListener()
  {
    public void widgetDisposed(DisposeEvent e)
    {
      dispose();
    }
  };

  private IListener adminListener = new IListener()
  {
    public void notifyEvent(IEvent event)
    {
      ViewerUtil.refresh(repositoryTableViewer, null);
    }
  };

  private IListener adminManagerListener = new ContainerEventAdapter<CDOAdminClient>()
  {
    @Override
    protected void onAdded(IContainer<CDOAdminClient> container, CDOAdminClient admin)
    {
      admin.addListener(adminListener);
    }

    @Override
    protected void onRemoved(IContainer<CDOAdminClient> container, CDOAdminClient admin)
    {
      admin.removeListener(adminListener);
    }
  };

  private CDOAdminClientManager adminManager;

  private IManagedContainer container;

  private Composite parent;

  private Text hostText;

  private ValidatingText portText;

  private TableViewer repositoryTableViewer;

  private ValidatingText repositoryNameText;

  private Label userNameLabel;

  private Text userNameText;

  private Label passwordLabel;

  private Text passwordText;

  private String connectorDescription;

  private String repositoryName;

  private String userName;

  private String password;

  private VersioningMode versioningMode;

  private IDGeneration idGeneration;

  public MasterRepositoryController(Composite parent)
  {
    this.parent = parent;

    container = ContainerUtil.createPluginContainer();
    LifecycleUtil.activate(container);

    adminManager = CDOAdminClientUtil.createAdminManager(container);
    adminManager.addListener(adminManagerListener);
    LifecycleUtil.activate(adminManager);

    AbstractRepositoryPage.createLabel(parent, "Host:");
    hostText = new Text(parent, SWT.BORDER);
    hostText.setText("localhost");
    hostText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

    AbstractRepositoryPage.createLabel(parent, "Port:");
    portText = new HostValidatingText(parent);
    portText.setText("2036");
    hostText.addModifyListener(portText);

    AbstractRepositoryPage.createLabel(parent, "Repositories:");
    repositoryTableViewer = new TableViewer(parent, SWT.BORDER | SWT.SINGLE);
    repositoryTableViewer.setContentProvider(new AdminContentProvider());
    repositoryTableViewer.setLabelProvider(new AdminLabelProvider());
    repositoryTableViewer.setInput(adminManager);
    repositoryTableViewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    repositoryTableViewer.addSelectionChangedListener(new ISelectionChangedListener()
    {
      public void selectionChanged(SelectionChangedEvent event)
      {
        IStructuredSelection selection = (IStructuredSelection)event.getSelection();
        CDOAdminClientRepository adminRepository = (CDOAdminClientRepository)selection.getFirstElement();
        if (adminRepository != null)
        {
          repositoryNameText.setText(adminRepository.getName());
          repositoryNameText.modifyText(false);
        }
      }
    });

    AbstractRepositoryPage.createLabel(parent, "Repository name:");
    repositoryNameText = new RepositoryValidatingText(parent);

    userNameLabel = AbstractRepositoryPage.createLabel(parent, "User name:");
    userNameText = new Text(parent, SWT.BORDER);
    userNameText.setLayoutData(createWidthGridData());
    userNameText.addModifyListener(new ModifyListener()
    {
      public void modifyText(ModifyEvent e)
      {
        userName = userNameText.getText();
        repositoryNameText.modifyText(true);
      }
    });

    passwordLabel = AbstractRepositoryPage.createLabel(parent, "Password:");
    passwordText = new Text(parent, SWT.BORDER | SWT.PASSWORD);
    passwordText.setLayoutData(createWidthGridData());
    passwordText.addModifyListener(new ModifyListener()
    {
      public void modifyText(ModifyEvent e)
      {
        password = passwordText.getText();
        repositoryNameText.modifyText(true);
      }
    });

    portText.modifyText(false);
    repositoryNameText.modifyText(false);

    parent.addDisposeListener(disposeListener);
  }

  public final String getConnectorDescription()
  {
    return connectorDescription;
  }

  public final String getRepositoryName()
  {
    return repositoryName;
  }

  public final String getUserName()
  {
    return userName;
  }

  public final String getPassword()
  {
    return password;
  }

  public final VersioningMode getVersioningMode()
  {
    return versioningMode;
  }

  public final IDGeneration getIDGeneration()
  {
    return idGeneration;
  }

  public final boolean isValid()
  {
    return portText.isValid() && repositoryNameText.isValid();
  }

  public void dispose()
  {
    parent.removeDisposeListener(disposeListener);

    if (container != null)
    {
      repositoryNameText.cancelValidation();
      portText.cancelValidation();

      LifecycleUtil.deactivate(adminManager);
      adminManager = null;

      container.deactivate();
      container = null;
    }
  }

  protected void validateController()
  {
    if (repositoryNameText != null)
    {
      repositoryName = repositoryNameText.getText();
    }
  }

  protected void showCredentials(final boolean show)
  {
    parent.getDisplay().asyncExec(new Runnable()
    {
      public void run()
      {
        if (!parent.isDisposed())
        {
          userNameLabel.setEnabled(show);
          userNameText.setEnabled(show);
          passwordLabel.setEnabled(show);
          passwordText.setEnabled(show);
        }
      }
    });
  }

  private static GridData createWidthGridData()
  {
    GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false);
    gridData.widthHint = VALIDATING_WIDTH;
    return gridData;
  }

  /**
   * @author Eike Stepper
   */
  private abstract class ValidatingText extends Composite implements ModifyListener
  {
    private Text text;

    private Label imageLabel;

    private Label statusLabel;

    private boolean valid;

    private ValidationThread validationThread;

    public ValidatingText(Composite parent)
    {
      super(parent, SWT.NONE);
      setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

      GridLayout layout = new GridLayout(3, false);
      layout.marginWidth = 0;
      layout.marginHeight = 0;
      setLayout(layout);

      text = new Text(this, SWT.BORDER);
      text.setLayoutData(createWidthGridData());
      text.addModifyListener(this);

      imageLabel = new Label(this, SWT.NONE);

      statusLabel = new Label(this, SWT.NONE);
      statusLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    }

    public final String getText()
    {
      return text.getText();
    }

    public final void setText(String text)
    {
      this.text.setText(text);
    }

    public final boolean isValid()
    {
      return valid;
    }

    public void cancelValidation()
    {
      if (validationThread != null)
      {
        validationThread.cancel();
        validationThread = null;
      }
    }

    public void modifyText(ModifyEvent e)
    {
      modifyText(true);
    }

    public void modifyText(boolean delay)
    {
      validateController();

      imageLabel.setImage(EMPTY_IMAGE);
      statusLabel.setText("");

      cancelValidation();

      parent.getDisplay().timerExec(delay ? 400 : 0, new Runnable()
      {
        public void run()
        {
          if (!parent.isDisposed())
          {
            String validationInfo = getValidationInfo();
            if (validationInfo != null)
            {
              validationThread = new ValidationThread(validationInfo);
              validationThread.start();
            }
            else
            {
              finished(false);
            }
          }
        }
      });
    }

    protected abstract String getValidationInfo();

    protected abstract String validate(String validationInfo) throws Exception;

    protected void finished(boolean valid)
    {
    }

    /**
     * @author Eike Stepper
     */
    private final class ValidationThread extends Thread
    {
      private final String validationInfo;

      private boolean canceled;

      public ValidationThread(String validationInfo)
      {
        super("Host Validator");
        setDaemon(true);

        this.validationInfo = validationInfo;
      }

      public void cancel()
      {
        canceled = true;
        interrupt();
      }

      @Override
      public void run()
      {
        updateLabels(null, false);
        String message = null;
        valid = false;

        try
        {
          message = validate(validationInfo);

          if (!canceled)
          {
            valid = true;
          }
        }
        catch (Exception ex)
        {
          message = ex.getMessage();
        }

        if (canceled)
        {
          return;
        }

        updateLabels(message, valid);
      }

      private void updateLabels(final String message, final boolean valid)
      {
        Display display = parent.getDisplay();
        if (!parent.isDisposed())
        {
          display.syncExec(new Runnable()
          {
            public void run()
            {
              try
              {
                if (message != null)
                {
                  imageLabel.setImage(valid ? OK_IMAGE : ERROR_IMAGE);
                  statusLabel.setText(message);
                  finished(valid);
                }
              }
              catch (Exception ex)
              {
                //$FALL-THROUGH$
              }

              validateController();
            }
          });
        }
      }
    }
  }

  /**
   * @author Eike Stepper
   */
  private final class HostValidatingText extends ValidatingText
  {
    public HostValidatingText(Composite parent)
    {
      super(parent);
    }

    @Override
    protected String getValidationInfo()
    {
      connectorDescription = null;

      String host = hostText.getText();
      if (host.length() == 0)
      {
        return null;
      }

      String port = getText();
      if (port.length() == 0)
      {
        port = "2036";
      }

      return host + ":" + port;
    }

    @Override
    protected String validate(String validationInfo) throws Exception
    {
      String[] tokens = validationInfo.split(":");
      String host = tokens[0];
      String port = tokens[1];

      InetAddress addr;

      try
      {
        addr = InetAddress.getByName(host);
      }
      catch (Exception ex)
      {
        throw new Exception("Unknown host");
      }

      try
      {
        new InetSocketAddress(addr, Integer.parseInt(port));
      }
      catch (IllegalArgumentException ex)
      {
        throw new Exception("Invalid port");
      }

      connectorDescription = validationInfo;
      return "Valid address";
    }

    @Override
    protected void finished(boolean valid)
    {
      repositoryNameText.modifyText(false);

      if (valid && connectorDescription != null)
      {
        adminManager.addConnection("tcp://" + connectorDescription);
      }

      ViewerUtil.refresh(repositoryTableViewer, null);
    }
  }

  /**
   * @author Eike Stepper
   */
  private final class RepositoryValidatingText extends ValidatingText
  {
    private boolean authenticating;

    public RepositoryValidatingText(Composite parent)
    {
      super(parent);
    }

    @Override
    protected String getValidationInfo()
    {
      if (connectorDescription == null)
      {
        return null;
      }

      String repositoryName = getText();
      if (repositoryName.length() == 0)
      {
        return null;
      }

      return repositoryName;
    }

    @Override
    protected String validate(String repositoryName) throws Exception
    {
      CDONet4jSession session = null;
      authenticating = false;

      versioningMode = null;
      idGeneration = null;

      try
      {
        IConnector connector = getConnector();
        IPasswordCredentialsProvider credentialsProvider = new PasswordCredentialsProvider(userName, password)
        {
          @Override
          public IPasswordCredentials getCredentials()
          {
            authenticating = true;
            return super.getCredentials();
          }
        };

        try
        {
          CDONet4jSessionConfiguration config = CDONet4jUtil.createNet4jSessionConfiguration();
          config.setConnector(connector);
          config.setRepositoryName(repositoryName);
          config.setCredentialsProvider(credentialsProvider);

          session = config.openNet4jSession();
          if (session != null && session.isClosed())
          {
            session = null;
          }
        }
        catch (NotAuthenticatedException ex)
        {
          authenticating = true;
        }
        catch (Exception ex)
        {
          session = null;
        }

        if (session == null)
        {
          showCredentials(true);
          if (authenticating)
          {
            throw new Exception("Authentication failed");
          }

          throw new Exception("Repository unreachable");
        }

        showCredentials(authenticating);

        CDORepositoryInfo repositoryInfo = session.getRepositoryInfo();
        versioningMode = VersioningMode.from(repositoryInfo);
        idGeneration = IDGeneration.from(repositoryInfo);

        String message = versioningMode.toString();
        if (versioningMode == VersioningMode.Branching && idGeneration == IDGeneration.UUID)
        {
          message += ", Replicable";
        }

        return message;
      }
      finally
      {
        LifecycleUtil.deactivate(session);
      }
    }

    private IConnector getConnector() throws Exception
    {
      IConnector connector = null;

      try
      {
        connector = Net4jUtil.getConnector(container, "tcp", connectorDescription);
      }
      catch (Exception ex)
      {
        connector = null;
      }

      if (connector == null)
      {
        throw new Exception("Host unreachable");
      }

      return connector;
    }
  }

  /**
   * @author Eike Stepper
   */
  private final class AdminContentProvider implements IStructuredContentProvider
  {
    public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
    {
    }

    public void dispose()
    {
    }

    public Object[] getElements(Object inputElement)
    {
      if (connectorDescription != null)
      {
        for (CDOAdminClient admin : adminManager.getConnections())
        {
          String url = admin.getURL();
          if (url.equals("tcp://" + connectorDescription))
          {
            return admin.getRepositories();
          }
        }
      }

      return ContainerItemProvider.NO_ELEMENTS;
    }
  }

  /**
   * @author Eike Stepper
   */
  private final class AdminLabelProvider extends LabelProvider
  {
    @Override
    public Image getImage(Object element)
    {
      if (element instanceof CDOAdminClientRepository)
      {
        return REPOSITORY_IMAGE;
      }

      return super.getImage(element);
    }

    @Override
    public String getText(Object element)
    {
      if (element instanceof CDOAdminClientRepository)
      {
        CDOAdminClientRepository adminRepository = (CDOAdminClientRepository)element;
        return adminRepository.getName();
      }

      return super.getText(element);
    }
  }
}

Back to the top