mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Violette Roche-Montane
26.15.2014 afa089fedd62a29826d57cc34293ad5e0e6a4efd
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2006-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2011-2014 ForgeRock AS
 */
 
package org.opends.quicksetup.ui;
 
import org.opends.quicksetup.event.ButtonActionListener;
import org.opends.quicksetup.event.ProgressUpdateListener;
import org.opends.quicksetup.event.ButtonEvent;
import org.opends.quicksetup.event.ProgressUpdateEvent;
import org.opends.quicksetup.*;
import org.opends.quicksetup.util.ProgressMessageFormatter;
import org.opends.quicksetup.util.HtmlProgressMessageFormatter;
import org.opends.quicksetup.util.BackgroundTask;
import org.opends.server.util.SetupUtils;
 
import static org.opends.quicksetup.util.Utils.*;
import org.forgerock.i18n.LocalizableMessageBuilder;
import org.forgerock.i18n.LocalizableMessage;
import static org.opends.messages.QuickSetupMessages.*;
import static com.forgerock.opendj.util.OperatingSystem.isMacOS;
 
import javax.swing.*;
 
import java.awt.Cursor;
import java.util.ArrayList;
import java.util.List;
import org.forgerock.i18n.slf4j.LocalizedLogger;
 
import java.util.logging.Handler;
import java.util.Map;
 
/**
 * This class is responsible for doing the following:
 *
 * Check whether we are installing or uninstalling and which type of
 * installation we are running.
 *
 * Performs all the checks and validation of the data provided by the user
 * during the setup.
 *
 * It will launch also the installation once the user clicks on 'Finish' if we
 * are installing the product.
 *
 * If we are running a web start installation it will start the background
 * downloading of the jar files that are required to perform the installation
 * (OpenDS.jar, je.jar, etc.).  The global idea is to force the user to
 * download just one jar file (quicksetup.jar) to launch the Web Start
 * installer.  Until this class is not finished the WebStart Installer will be
 * on the ProgressStep.DOWNLOADING step.
 *
 */
public class QuickSetup implements ButtonActionListener, ProgressUpdateListener
{
 
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  private GuiApplication application;
 
  private CurrentInstallStatus installStatus;
 
  private WizardStep currentStep;
 
  private QuickSetupDialog dialog;
 
  private LocalizableMessageBuilder progressDetails = new LocalizableMessageBuilder();
 
  private ProgressDescriptor lastDescriptor;
 
  private ProgressDescriptor lastDisplayedDescriptor;
 
  private ProgressDescriptor descriptorToDisplay;
 
  // Update period of the dialogs.
  private static final int UPDATE_PERIOD = 500;
 
  // The full pathname of the MacOS X LaunchServices OPEN(1) helper.
  private static final String MAC_APPLICATIONS_OPENER = "/usr/bin/open";
 
  /**
   * This method creates the install/uninstall dialogs and to check the current
   * install status. This method must be called outside the event thread because
   * it can perform long operations which can make the user think that the UI is
   * blocked.
   *
   * @param args for the moment this parameter is not used but we keep it in
   * order to (in case of need) pass parameters through the command line.
   */
  public void initialize(String[] args)
  {
    ProgressMessageFormatter formatter = new HtmlProgressMessageFormatter();
 
    installStatus = new CurrentInstallStatus();
 
    application = Application.create();
    application.setProgressMessageFormatter(formatter);
    application.setCurrentInstallStatus(installStatus);
    if (args != null)
    {
      application.setUserArguments(args);
    }
    else
    {
      application.setUserArguments(new String[]{});
    }
    try
    {
      initLookAndFeel();
    }
    catch (Throwable t)
    {
      // This is likely a bug.
      t.printStackTrace();
    }
 
    /* In the calls to setCurrentStep the dialog will be created */
      setCurrentStep(application.getFirstWizardStep());
  }
 
  /**
   * This method displays the setup dialog. This method must be called from the
   * event thread.
   */
  public void display()
  {
    getDialog().packAndShow();
  }
 
  /**
   * ButtonActionListener implementation. It assumes that we are called in the
   * event thread.
   *
   * @param ev the ButtonEvent we receive.
   */
  public void buttonActionPerformed(ButtonEvent ev)
  {
    switch (ev.getButtonName())
    {
    case NEXT:
      nextClicked();
      break;
 
    case CLOSE:
      closeClicked();
      break;
 
    case FINISH:
      finishClicked();
      break;
 
    case QUIT:
      quitClicked();
      break;
 
    case CONTINUE_INSTALL:
      continueInstallClicked();
      break;
 
    case PREVIOUS:
      previousClicked();
      break;
 
    case LAUNCH_STATUS_PANEL:
      launchStatusPanelClicked();
      break;
 
    case INPUT_PANEL_BUTTON:
      inputPanelButtonClicked();
      break;
 
    default:
      throw new IllegalArgumentException("Unknown button name: "
          + ev.getButtonName());
    }
  }
 
  /**
   * ProgressUpdateListener implementation. Here we take the
   * ProgressUpdateEvent and create a ProgressDescriptor that
   * will be used to update the progress dialog.
   *
   * @param ev the ProgressUpdateEvent we receive.
   *
   * @see #runDisplayUpdater()
   */
  public void progressUpdate(ProgressUpdateEvent ev)
  {
    synchronized (this)
    {
      ProgressDescriptor desc = createProgressDescriptor(ev);
      boolean isLastDescriptor = desc.getProgressStep().isLast();
      if (isLastDescriptor)
      {
        lastDescriptor = desc;
      }
 
      descriptorToDisplay = desc;
    }
  }
 
  /**
   * This method is used to update the progress dialog.
   *
   * We are receiving notifications from the installer and uninstaller (this
   * class is a ProgressListener). However if we lots of notifications updating
   * the progress panel every time we get a progress update can result of a lot
   * of flickering. So the idea here is to have a minimal time between 2 updates
   * of the progress dialog (specified by UPDATE_PERIOD).
   *
   * @see #progressUpdate(org.opends.quicksetup.event.ProgressUpdateEvent)
   */
  private void runDisplayUpdater()
  {
    boolean doPool = true;
    while (doPool)
    {
      try
      {
        Thread.sleep(UPDATE_PERIOD);
      } catch (Exception ex)
      {
      }
      synchronized (this) {
        final ProgressDescriptor desc = descriptorToDisplay;
        if (desc != null) {
          if (desc != lastDisplayedDescriptor) {
            lastDisplayedDescriptor = desc;
 
            SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                if (application.isFinished() &&
                    !getCurrentStep().isFinishedStep())
                {
                  setCurrentStep(application.getFinishedStep());
                }
                getDialog().displayProgress(desc);
              }
            });
          }
          doPool = desc != lastDescriptor;
        }
      }
    }
  }
 
  /**
   * Method called when user clicks 'Next' button of the wizard.
   *
   */
  private void nextClicked()
  {
    final WizardStep cStep = getCurrentStep();
    application.nextClicked(cStep, this);
    BackgroundTask<?> worker = new NextClickedBackgroundTask(cStep);
    getDialog().workerStarted();
    worker.startBackgroundTask();
  }
 
  private void updateUserData(final WizardStep cStep) {
    BackgroundTask<?> worker = new BackgroundTask<Object>() {
      public Object processBackgroundTask() throws UserDataException {
        try {
          application.updateUserData(cStep, QuickSetup.this);
        }
        catch (UserDataException uide) {
          throw uide;
        }
        catch (Throwable t) {
          throw new UserDataException(cStep,
                  getThrowableMsg(INFO_BUG_MSG.get(), t));
        }
        return null;
      }
 
      public void backgroundTaskCompleted(Object returnValue,
                                          Throwable throwable) {
        getDialog().workerFinished();
 
        if (throwable != null) {
          UserDataException ude = (UserDataException) throwable;
          if (ude instanceof UserDataConfirmationException)
          {
            if (displayConfirmation(ude.getMessageObject(),
                INFO_CONFIRMATION_TITLE.get()))
            {
              try
              {
              setCurrentStep(application.getNextWizardStep(cStep));
              }
              catch (Throwable t)
              {
                t.printStackTrace();
              }
            }
          }
          else
          {
            displayError(ude.getMessageObject(), INFO_ERROR_TITLE.get());
          }
        } else {
          setCurrentStep(application.getNextWizardStep(cStep));
        }
        if (currentStep.isProgressStep()) {
          launch();
        }
      }
    };
    getDialog().workerStarted();
    worker.startBackgroundTask();
  }
 
  /**
   * Method called when user clicks 'Finish' button of the wizard.
   *
   */
  private void finishClicked()
  {
    final WizardStep cStep = getCurrentStep();
    if (application.finishClicked(cStep, this)) {
      updateUserData(cStep);
    }
  }
 
  /**
   * Method called when user clicks 'Previous' button of the wizard.
   *
   */
  private void previousClicked()
  {
    WizardStep cStep = getCurrentStep();
    application.previousClicked(cStep, this);
    setCurrentStep(application.getPreviousWizardStep(cStep));
  }
 
  /**
   * Method called when user clicks 'Quit' button of the wizard.
   *
   */
  private void quitClicked()
  {
    WizardStep cStep = getCurrentStep();
    application.quitClicked(cStep, this);
  }
 
  /**
   * Method called when user clicks 'Continue' button in the case where there
   * is something installed.
   */
  private void continueInstallClicked()
  {
    // TODO:  move this stuff to Installer?
    application.forceToDisplay();
    getDialog().forceToDisplay();
    setCurrentStep(Step.WELCOME);
  }
 
  /**
   * Method called when user clicks 'Close' button of the wizard.
   *
   */
  private void closeClicked()
  {
    WizardStep cStep = getCurrentStep();
    application.closeClicked(cStep, this);
  }
 
  private void launchStatusPanelClicked()
  {
    BackgroundTask<Object> worker = new BackgroundTask<Object>()
    {
      public Object processBackgroundTask() throws UserDataException {
        try
        {
          Installation installation;
          if (isWebStart()) {
            String installDir = application.getUserData().getServerLocation();
            installation =
              new Installation(installDir, installDir);
          } else {
            installation = Installation.getLocal();
          }
          ProcessBuilder pb;
          if (isMacOS()) {
            List<String> cmd = new ArrayList<String>();
            cmd.add(MAC_APPLICATIONS_OPENER);
            cmd.add(getScriptPath(
                getPath(installation.getControlPanelCommandFile())));
            pb = new ProcessBuilder(cmd);
          } else {
            String cmd = getScriptPath(
                getPath(installation.getControlPanelCommandFile()));
            pb = new ProcessBuilder(cmd);
          }
          Map<String, String> env = pb.environment();
          env.put(SetupUtils.OPENDJ_JAVA_HOME, System.getProperty("java.home"));
          Process process = pb.start();
          /**
           * Wait for 3 seconds.  Assume that if the process has not exited
           * everything went fine.
           */
          int returnValue = 0;
          try
          {
            Thread.sleep(3000);
          }
          catch (Throwable t)
          {
          }
          try
          {
            returnValue = process.exitValue();
          }
          catch (IllegalThreadStateException e)
          {
            // The process has not exited: assume that the status panel could
            // be launched successfully.
          }
 
          if (returnValue != 0)
          {
            throw new Error(
                    INFO_COULD_NOT_LAUNCH_CONTROL_PANEL_MSG.get().toString());
          }
        }
        catch (Throwable t)
        {
          // This looks like a bug
          t.printStackTrace();
          throw new Error(
              INFO_COULD_NOT_LAUNCH_CONTROL_PANEL_MSG.get().toString());
        }
        return null;
      }
 
      public void backgroundTaskCompleted(Object returnValue,
          Throwable throwable)
      {
        getDialog().getFrame().setCursor(
            Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
 
        if (throwable != null)
        {
          displayError(LocalizableMessage.raw(throwable.getMessage()),
                  INFO_ERROR_TITLE.get());
        }
      }
    };
    getDialog().getFrame().setCursor(
        Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    worker.startBackgroundTask();
  }
 
  /**
   * This method tries to update the visibility of the steps panel.  The
   * contents are updated because the user clicked in one of the buttons
   * that could make the steps panel to change.
   *
   */
  private void inputPanelButtonClicked()
  {
    getDialog().getStepsPanel().updateStepVisibility(this);
  }
 
  /**
   * Method called when we want to quit the setup (for instance when the user
   * clicks on 'Close' or 'Quit' buttons and has confirmed that (s)he wants to
   * quit the program.
   *
   */
  public void quit()
  {
    logger.info(LocalizableMessage.raw("quitting application"));
    flushLogs();
    System.exit(0);
  }
 
  private void flushLogs() {
    java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(logger.getName());
    Handler[] handlers = julLogger.getHandlers();
    if (handlers != null) {
      for (Handler h : handlers) {
        h.flush();
      }
    }
  }
 
  /**
   * Launch the QuickSetup application Open DS.
   */
  public void launch()
  {
    application.addProgressUpdateListener(this);
    new Thread(application, "Application Thread").start();
    Thread t = new Thread(new Runnable()
    {
      public void run()
      {
        runDisplayUpdater();
        WizardStep ws = application.getCurrentWizardStep();
        getDialog().getButtonsPanel().updateButtons(ws);
      }
    });
    t.start();
  }
 
  /**
   * Get the current step.
   *
   * @return the currently displayed Step of the wizard.
   */
  private WizardStep getCurrentStep()
  {
    return currentStep;
  }
 
  /**
   * Set the current step. This will basically make the required calls in the
   * dialog to display the panel that corresponds to the step passed as
   * argument.
   *
   * @param step The step to be displayed.
   */
  public void setCurrentStep(WizardStep step)
  {
    if (step == null)
    {
      throw new NullPointerException("step is null");
    }
    currentStep = step;
    application.setDisplayedWizardStep(step, application.getUserData(),
        getDialog());
  }
 
  /**
   * Get the dialog that is displayed.
   *
   * @return the dialog.
   */
  public QuickSetupDialog getDialog()
  {
    if (dialog == null)
    {
      dialog = new QuickSetupDialog(application,
              installStatus, this);
      dialog.addButtonActionListener(this);
      application.setQuickSetupDialog(dialog);
    }
    return dialog;
  }
 
  /**
   * Displays an error message dialog.
   *
   * @param msg
   *          the error message.
   * @param title
   *          the title for the dialog.
   */
  public void displayError(LocalizableMessage msg, LocalizableMessage title)
  {
    if (isCli()) {
      System.err.println(msg);
    } else {
      getDialog().displayError(msg, title);
    }
  }
 
  /**
   * Displays a confirmation message dialog.
   *
   * @param msg
   *          the confirmation message.
   * @param title
   *          the title of the dialog.
   * @return <CODE>true</CODE> if the user confirms the message, or
   * <CODE>false</CODE> if not.
   */
  public boolean displayConfirmation(LocalizableMessage msg, LocalizableMessage title)
  {
    return getDialog().displayConfirmation(msg, title);
  }
 
  /**
   * Gets the string value for a given field name.
   *
   * @param fieldName
   *          the field name object.
   * @return the string value for the field name.
   */
  public String getFieldStringValue(FieldName fieldName)
  {
    String sValue = null;
 
    Object value = getFieldValue(fieldName);
    if (value != null)
    {
      if (value instanceof String)
      {
        sValue = (String) value;
      } else
      {
        sValue = String.valueOf(value);
      }
    }
    return sValue;
  }
 
  /**
   * Gets the value for a given field name.
   *
   * @param fieldName
   *          the field name object.
   * @return the value for the field name.
   */
  public Object getFieldValue(FieldName fieldName)
  {
    return getDialog().getFieldValue(fieldName);
  }
 
  /**
   * Marks the fieldName as valid or invalid depending on the value of the
   * invalid parameter. With the current implementation this implies basically
   * using a red color in the label associated with the fieldName object. The
   * color/style used to mark the label invalid is specified in UIFactory.
   *
   * @param fieldName
   *          the field name object.
   * @param invalid
   *          whether to mark the field valid or invalid.
   */
  public void displayFieldInvalid(FieldName fieldName, boolean invalid)
  {
    getDialog().displayFieldInvalid(fieldName, invalid);
  }
 
  /**
   * A method to initialize the look and feel.
   *
   */
  private void initLookAndFeel() throws Throwable
  {
    UIFactory.initialize();
  }
 
  /**
   * A methods that creates an ProgressDescriptor based on the value of a
   * ProgressUpdateEvent.
   *
   * @param ev
   *          the ProgressUpdateEvent used to generate the
   *          ProgressDescriptor.
   * @return the ProgressDescriptor.
   */
  private ProgressDescriptor createProgressDescriptor(ProgressUpdateEvent ev)
  {
    ProgressStep status = ev.getProgressStep();
    LocalizableMessage newProgressLabel = ev.getCurrentPhaseSummary();
    LocalizableMessage additionalDetails = ev.getNewLogs();
    Integer ratio = ev.getProgressRatio();
 
    if (additionalDetails != null)
    {
      progressDetails.append(additionalDetails);
    }
    /*
    Note: progressDetails might have a certain number of characters that
    break LocalizableMessage Formatter (for instance percentages).  When fix for
    issue 2142 was committed it broke this code.  So here
    we use LocalizableMessage.raw instead of calling directly progressDetails.toMessage
    */
    return new ProgressDescriptor(status, ratio, newProgressLabel,
        LocalizableMessage.raw(progressDetails.toString()));
  }
 
  /**
   * This is a class used when the user clicks on next and that extends
   * BackgroundTask.
   */
  private class NextClickedBackgroundTask extends BackgroundTask<Object>
  {
    private WizardStep cStep;
    public NextClickedBackgroundTask(WizardStep cStep)
    {
      this.cStep = cStep;
    }
 
    public Object processBackgroundTask() throws UserDataException {
      try {
        application.updateUserData(cStep, QuickSetup.this);
      }
      catch (UserDataException uide) {
        throw uide;
      }
      catch (Throwable t) {
        throw new UserDataException(cStep,
                getThrowableMsg(INFO_BUG_MSG.get(), t));
      }
      return null;
    }
 
    public void backgroundTaskCompleted(Object returnValue,
                                        Throwable throwable) {
      getDialog().workerFinished();
 
      if (throwable != null)
      {
        if (!(throwable instanceof UserDataException))
        {
          logger.warn(LocalizableMessage.raw("Unhandled exception.", throwable));
        }
        else
        {
          UserDataException ude = (UserDataException) throwable;
          if (ude instanceof UserDataConfirmationException)
          {
            if (displayConfirmation(ude.getMessageObject(),
                INFO_CONFIRMATION_TITLE.get()))
            {
              setCurrentStep(application.getNextWizardStep(cStep));
            }
          }
          else if (ude instanceof UserDataCertificateException)
          {
            final UserDataCertificateException ce =
              (UserDataCertificateException)ude;
            CertificateDialog dlg =
              new CertificateDialog(getDialog().getFrame(), ce);
            dlg.pack();
            dlg.setVisible(true);
            CertificateDialog.ReturnType answer = dlg.getUserAnswer();
            if (answer != CertificateDialog.ReturnType.NOT_ACCEPTED)
            {
              /*
               * Retry the click but now with the certificate accepted.
               */
              application.acceptCertificateForException(ce,
                  answer == CertificateDialog.ReturnType.ACCEPTED_PERMANENTLY);
              application.nextClicked(cStep, QuickSetup.this);
              BackgroundTask<Object> worker =
                new NextClickedBackgroundTask(cStep);
              getDialog().workerStarted();
              worker.startBackgroundTask();
            }
          }
          else
          {
            displayError(ude.getMessageObject(), INFO_ERROR_TITLE.get());
          }
        }
      } else {
        setCurrentStep(application.getNextWizardStep(cStep));
      }
    }
  }
}